通過將cornerRadius
應用於UIImageView
的圖層,並通過borderWith
和borderColor
添加邊框,我正在繪製圓形頭像圖片。像這樣:iOS:具有邊框出血顏色的圓角矩形
self.layer.masksToBounds = YES;
self.layer.cornerRadius = imageDimension/2.f;
self.layer.borderWidth = 1.f;
self.layer.borderColor = borderColor.CGColor;
,除了內容的這個小,但明顯的出血境外的偉大工程,是這樣的:
有沒有辦法,只是一開始就邊界由幾十分之一,還是插入的內容超過了邊界?
解決方案
感謝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
你可以嘗試透明的1個像素的邊框添加到您的圖像文件,所以你的形象將是2個像素寬和高,這應該與混合 – dariaa