在开发过程中,经常会遇到过圆角的控件,如头像,按钮,这一类的需求一般都是定义4个角都是圆角,只需定义它图层的圆角度就行
设置View边框宽度
UIView * view= [[UIView alloc]initWithFrame:CGRectMake(100,100,100,100)];
view.backgroundColor= [UIColor blueColor];
view.layer.cornerRadius=10;
view.layer.borderColor=[UIColor redColor].CGColor;
view.layer.borderWidth=1;
[self.view addSubview:view];
以上代码就是为View添加一个角度为10的圆角
设置View边框颜色
view.layer.borderColor=[UIColor redColor].CGColor;
设置View边框宽度
view.layer.borderWidth=1;
如果设置图片,发现角没有发生变化,你可以设置图片layer.masksToBounds的属性为YES即可
headImage.layer.maskToBounds=YES
+ (UIBezierPath *)bezierPathWithRoundedRect:(CGRect)rect byRoundingCorners:(UIRectCorner)corners cornerRadii:(CGSize)cornerRadii
这个方法就可以轻松添加圆角遮罩其代码如下
UIView * view= [[UIView alloc]initWithFrame:CGRectMake(100,100,100,100)];
view.backgroundColor= [UIColor blueColor];
[self.view addSubview:view];
UIBezierPath*maskPath = [UIBezierPath bezierPathWithRoundedRect:view.bounds byRoundingCorners:
UIRectCornerBottomLeft|UIRectCornerBottomRight
cornerRadii:CGSizeMake(10,10)];
CAShapeLayer*maskLayer = [[CAShapeLayer alloc]init];
maskLayer.frame= view.bounds;
maskLayer.path= maskPath.CGPath;
view.layer.mask= maskLayer;
这样,设置出来的View就可以指定某个或某几个角为圆角
其中byRounding 是设置指定哪个是圆角,如果是多个角,用"|"分割,有以下四个选项
UIRectCornerTopLeft 左上
UIRectCornerTopRight 右上
UIRectCornerBottomLeft 左下
UIRectCornerBottomRight 右下
cornerRadii:CGSizeMake(5,5) 是设置圆角的程度