Believe in your own future, will thank yourself right now Sinner Yun

Sinner_Yun

iOS 部分圆角+边框的实现(防边框被切)

部分圆角可以通过 layer 的 mask 属性实现。

1. 创建 UIBezierPath

关键参数 corners,由于是 NS_OPTIONS枚举,所以可以使用位运算来达到设置多个圆角。

 1 /* corners 的可能值
 2 typedef NS_OPTIONS(NSUInteger, UIRectCorner) {
 3     UIRectCornerTopLeft     = 1 << 0,
 4     UIRectCornerTopRight    = 1 << 1,
 5     UIRectCornerBottomLeft  = 1 << 2,
 6     UIRectCornerBottomRight = 1 << 3,
 7     UIRectCornerAllCorners  = ~0UL
 8 };
 9 */
10 UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:view.bounds byRoundingCorners:corners cornerRadii:CGSizeMake(cornerRadius, cornerRadius)];

2. 创建 maskLayer

view.layer.mask 属性会按照赋值的 layer 的 alpha 通道来遮盖 view 的 layer,即 alpha 为0的部分会被隐藏。

1 CAShapeLayer *maskLayer = [CAShapeLayer layer];
2 maskLayer.frame = view.bounds;
3 maskLayer.path = path.CGPath;
4 view.layer.mask = maskLayer;

如果在添加了部分圆角之后,如果想要添加边框,就不能使用 view.layer.cornerRadius 属性来实现,圆角部分会被裁剪。可以通过添加一层 subLayer 来实现。

3. 创建边框 layer

还可以通过修CAShapeLayerline 相关的属性,来改创建不同样式的边框。

1 CAShapeLayer *borderLayer = [CAShapeLayer layer];
2 borderLayer.frame = view.bounds;
3 borderLayer.path = path.CGPath;
4 borderLayer.lineWidth = borderWidth;
5 borderLayer.fillColor = [UIColor clearColor].CGColor;
6 borderLayer.strokeColor = borderColor.CGColor;
7 [view.layer addSublayer:borderLayer];

4. 效果 

 
 
 
 
 
 

作者:Mokyz
链接:https://www.jianshu.com/p/b7cae1208362
来源:简书

posted on 2021-02-22 14:55  Sinner_Yun  阅读(477)  评论(0编辑  收藏  举报

导航