如果需要將UIView的4個角全部都爲圓角,做法相當簡單,只需設置其Layer的cornerRadius屬性即可(項目需要使用QuartzCore框架)。而若要指定某幾個角(小於4)爲圓角而別的不變時,這種方法就不好用了。
一種簡單的實現方式 ,用到CAShapeLayer
UIView *redView = [[UIView alloc] initWithFrame:CGRectMake(120, 300, 80, 80)];
redView.backgroundColor = [UIColor redColor];
[self.view addSubview:redView];
UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:redView.bounds byRoundingCorners:UIRectCornerBottomLeft | UIRectCornerBottomRight cornerRadii:CGSizeMake(10, 10)];
// [UIBezierPath bezierPathWithRoundedRect:<#(CGRect)#> byRoundingCorners:<#(UIRectCorner)#> cornerRadii:<#(CGSize)#>]
// typedef NS_OPTIONS(NSUInteger, UIRectCorner) {
// UIRectCornerTopLeft = 1 << 0,
// UIRectCornerTopRight = 1 << 1,
// UIRectCornerBottomLeft = 1 << 2,
// UIRectCornerBottomRight = 1 << 3,
// UIRectCornerAllCorners = ~0UL
// };可以選擇任意幾個角
// cornerRadii 圓角的大小
CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
maskLayer.frame = redView.bounds;
maskLayer.path = maskPath.CGPath;
redView.layer.mask = maskLayer;