部分圓角可以通過 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
還可以通過修CAShapeLayer
與line
相關的屬性,來改創建不同樣式的邊框。
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
來源:簡書