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:
Is there a way to just outset the border by a few 1/10 points, or inset the content more than the border?
Solution
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
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…