部分圓角可以通過(guò) layer 的 mask 屬性實(shí)現(xiàn)。
1. 創(chuàng)建 UIBezierPath
關(guān)鍵參數(shù) corners,由于是 NS_OPTIONS枚舉,所以可以使用位運(yùn)算來(lái)達(dá)到設(shè)置多個(gè)圓角。
/* corners 的可能值
typedef NS_OPTIONS(NSUInteger, UIRectCorner) {
UIRectCornerTopLeft = 1 << 0,
UIRectCornerTopRight = 1 << 1,
UIRectCornerBottomLeft = 1 << 2,
UIRectCornerBottomRight = 1 << 3,
UIRectCornerAllCorners = ~0UL
};
*/
UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:view.bounds byRoundingCorners:corners cornerRadii:CGSizeMake(cornerRadius, cornerRadius)];
2. 創(chuàng)建 maskLayer
view.layer.mask 屬性會(huì)按照賦值的 layer 的 alpha 通道來(lái)遮蓋 view 的 layer,即 alpha 為0的部分會(huì)被隱藏。
CAShapeLayer *maskLayer = [CAShapeLayer layer];
maskLayer.frame = view.bounds;
maskLayer.path = path.CGPath;
view.layer.mask = maskLayer;
如果在添加了部分圓角之后,如果想要添加邊框,就不能使用 view.layer.cornerRadius 屬性來(lái)實(shí)現(xiàn),圓角部分會(huì)被裁剪??梢酝ㄟ^(guò)添加一層 subLayer 來(lái)實(shí)現(xiàn)。
3. 創(chuàng)建邊框 layer
還可以通過(guò)修CAShapeLayer與line 相關(guān)的屬性,來(lái)改創(chuàng)建不同樣式的邊框。
CAShapeLayer *borderLayer = [CAShapeLayer layer];
borderLayer.frame = view.bounds;
borderLayer.path = path.CGPath;
borderLayer.lineWidth = borderWidth;
borderLayer.fillColor = [UIColor clearColor].CGColor;
borderLayer.strokeColor = borderColor.CGColor;
[view.layer addSublayer:borderLayer];
4. 效果

image.png