前言:
我们在开发中经常会遇到将view变成圆角,实现起来很简单,我们一般都会使用这样的方式来完成:
rectView.layer.cornerRadius = 10.0f;
rectView.layer.masksToBounds = YES;
这样一写的话,我们的rectView的四个角都变成圆角了,但是有时候我们并不想要让它4个角都变成圆角,那么我们该怎么实现呢?
解决办法
答案是我们创建一个CAShapeLayer,并将其赋值给rectView的mask属性,设置CAShapeLayer的path属性为一个UIBezierPath,在创建UIBeizierPath的时候设置我们想要变换的角,例如:
- (void)viewDidLoad {
[super viewDidLoad];
[self addRectView];
}
- (void)addRectView
{
UIView *rectView = [[UIView alloc] initWithFrame:CGRectMake((self.view.frame.size.width-200)*0.5, (self.view.frame.size.height-100)*0.5, 200, 100)];
rectView.backgroundColor = [UIColor redColor];
UIRectCorner rectCorner = UIRectCornerTopLeft | UIRectCornerTopRight ;
UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:rectView.bounds byRoundingCorners:rectCorner cornerRadii:CGSizeMake(60, 100)];
CAShapeLayer *shapeLayer = [CAShapeLayer layer];
shapeLayer.path = path.CGPath;
rectView.layer.mask = shapeLayer;
[self.view addSubview:rectView];
}
效果如下:
注意点
如果把下面这个方法的第一个参数写成rectView.frame是看不到任何东西的
UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:rectView.bounds byRoundingCorners:rectCorner cornerRadii:CGSizeMake(60, 100)];
如果把
rectView.layer.mask = shapeLayer;
写成
[rectView.layer addSublayer:shapeLayer];
也是达不到我们想要的效果的。
我的理解是mask属性是切除多余的。
如果有疑问或者更好的修改圆角个数的方式,欢迎联系!