1.如果需要将UIView的4个角全部都为圆角,添加边框,做法相当简单,只需设置其Layer的cornerRadius、borderWidth、borderColor就可以了。
UIView *view = [[UIView alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];
view.layer.cornerRadius = 25;
view.layer.borderWidth = 1;
view.layer.borderColor = [UIColor redColor].CGColor;
[self.view addSubview:view];
2.如果要指定某几个角为圆角而别的不变时,最简单优雅的方案,就是使用UIBezierPath。
UIView *view = [[UIView alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];
[self.view addSubview:view];
view.backgroundColor = [UIColor lightGrayColor];
UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:view.bounds byRoundingCorners:UIRectCornerTopRight|UIRectCornerBottomLeft cornerRadii:CGSizeMake(25, 25)];
CAShapeLayer *mask = [CAShapeLayer layer];
mask.path = path.CGPath;
view.layer.mask = mask;
其中,参数:(UIRectCorner)corners指定了需要成为圆角的角,使用“|”来组合。
typedef NS_OPTIONS(NSUInteger, UIRectCorner) {
UIRectCornerTopLeft = 1 << 0,
UIRectCornerTopRight = 1 << 1,
UIRectCornerBottomLeft = 1 << 2,
UIRectCornerBottomRight = 1 << 3,
UIRectCornerAllCorners = ~0UL
};
3.给上面切了两个圆角的view增加边框。
如果直接设置borderWidth和borderColor,设置圆角的部分边线被贝塞尔曲线切掉。
解决思路:用UIBezierPath画好边框,在切圆角。
给view加了一个Category
- (void)applyRoundCorners:(UIRectCorner)corners radius:(CGFloat)radius
{
UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:self.bounds byRoundingCorners:corners cornerRadii:CGSizeMake(radius, radius)];
CAShapeLayer *temp = [CAShapeLayer layer];
temp.lineWidth = 2.f;
temp.fillColor = [UIColor clearColor].CGColor;
temp.strokeColor = [UIColor redColor].CGColor;
temp.frame = self.bounds;
temp.path = path.CGPath;
[self.layer addSublayer:temp];
CAShapeLayer *mask = [[CAShapeLayer alloc]initWithLayer:temp];
mask.path = path.CGPath;
self.layer.mask = mask;
}
使用示例:
UIView *view = [[UIView alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];
view.backgroundColor = [UIColor lightGrayColor];
[self.view addSubview:view];
[view applyRoundCorners:UIRectCornerTopRight|UIRectCornerBottomLeft radius:25];