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

iOS: Rounded rectangle with border bleeds color(iOS:带有边框出血颜色的圆角矩形)

本文介绍了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:带有边框出血颜色的圆角矩形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:iOS:带有边框出血颜色的圆角矩形

基础教程推荐