工作中经常需要将一个图形或者控件切为圆角,切为圆形或者四角都切为圆角的方法很常见也很简单,这里着重介绍一下切指定边角为圆角的方法
- (void)viewDidLoad {
[super viewDidLoad];
//1.四个角都切为圆角的方法很简单 , 直接:
UIView *view1 = [[UIView alloc] initWithFrame:CGRectMake(20, 100, 100, 100)];
view1.backgroundColor = [UIColor redColor];
[self.view addSubview:view1];
view1.layer.cornerRadius = 20.0f;
view1.layer.masksToBounds = YES;
//2.将指定的几个角切为圆角
UIView *view2 = [[UIView alloc] initWithFrame:CGRectMake(150, 100, 100, 100)];
view2.backgroundColor = [UIColor blueColor];
[self.view addSubview:view2];
UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:view2.bounds byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight cornerRadii:CGSizeMake(20, 20)];
CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
maskLayer.frame = view2.bounds;
maskLayer.path = maskPath.CGPath;
view2.layer.mask = maskLayer;
//3.将图形切为圆形 只需要将属性 cornerRadius 的值设置为为宽度的一半即可,因为 cornerRadius 属性指的就是半径
UIView *view3 = [[UIView alloc] initWithFrame:CGRectMake(280, 100, 100, 100)];
view3.backgroundColor = [UIColor greenColor];
[self.view addSubview:view3];
view3.layer.cornerRadius = view3.bounds.size.width * 0.5;
view3.layer.masksToBounds = YES;
}
附上效果图: