iOS:带边框的圆角矩形颜色 [英] iOS: Rounded rectangle with border bleeds color

查看:118
本文介绍了iOS:带边框的圆角矩形颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是将 cornerRadius 应用于 UIImageView 的图层,以及通过 borderWith borderColor 添加边框。像这样:

I'm drawing round avatar pics, by just applying cornerRadius to a UIImageView's layer, and also adding a border via borderWith and borderColor. Like so:

self.layer.masksToBounds = YES;
self.layer.cornerRadius = imageDimension / 2.f;
self.layer.borderWidth = 1.f;
self.layer.borderColor = borderColor.CGColor;

这种方法很有效,除了边界外的这种微小但明显的内容出血,如下所示:

That works great, except for this tiny, but noticeable bleeding of content outside the border, like this:

有没有办法让边界开始几个1/10点,或者内容多于边界?

Is there a way to just outset the border by a few 1/10 points, or inset the content more than the border?

感谢FelixLam,我提出了一个很好的解决方案,并留在这里为后世界:

Thanks to FelixLam, I came up with a nice solution and will leave it here for the afterworld:

@interface MMRoundImageViewWithBorder : UIView

- (id)initWithImage:(UIImage *)image borderWidth:(CGFloat)borderWidth;

@property (strong, nonatomic) UIImageView *imageView;
@property (assign, nonatomic) CGFloat borderWidth;
@property (strong, nonatomic) UIColor *borderColor;

@end

@implementation MMRoundImageViewWithBorder

- (id)initWithImage:(UIImage *)image borderWidth:(CGFloat)borderWidth {
    if (self = [super init]) {
        self.borderWidth = borderWidth;
        self.borderColor = UIColor.whiteColor;

        self.imageView = [[UIImageView alloc] initWithImage:image];
        [self addSubview:self.imageView];

        self.imageView.layer.masksToBounds = YES;
        self.layer.masksToBounds = YES;
    }
    return self;
}

- (void)setBorderColor:(UIColor *)borderColor {
    _borderColor = borderColor;
    self.backgroundColor = borderColor;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    [self refreshDimensions];
}

- (void)refreshDimensions {
    self.layer.cornerRadius = CGRectGetWidth(self.bounds) / 2.f;

    self.imageView.frame = CGRectInset(self.bounds, _borderWidth, _borderWidth);
    self.imageView.layer.cornerRadius = CGRectGetWidth(self.imageView.bounds) / 2.f;
}

- (void)setBorderWidth:(CGFloat)borderWidth {
    _borderWidth = borderWidth;
    [self refreshDimensions];
}

- (void)setFrame:(CGRect)frame {
    [super setFrame:frame];
    [self refreshDimensions];
}

@end


推荐答案

您可以尝试使用带圆形路径的 CAShapelayer 作为图层的蒙版,而不是使用角半径。

You could try to use a CAShapelayer with a circular path as the mask for the Layer instead of using the corner radius.

或者,您可以将图像视图放在一个容器中,该容器具有边框并且大一个/两个像素。

Alternatively you can place the image view in a container that has the border and is one/two pixel larger.

这篇关于iOS:带边框的圆角矩形颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆