iOS:带边框的圆角矩形颜色

man*_*mal 19 calayer uiimageview ios

我画圆形的头像图片,只把它运用cornerRadiusUIImageView的层,并且还通过添加边框borderWithborderColor.像这样:

self.layer.masksToBounds = YES;
self.layer.cornerRadius = imageDimension / 2.f;
self.layer.borderWidth = 1.f;
self.layer.borderColor = borderColor.CGColor;
Run Code Online (Sandbox Code Playgroud)

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

面膜和边框外的内容出血

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


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

@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
Run Code Online (Sandbox Code Playgroud)

Fel*_*oux 14

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

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