您的位置:首页 > 移动开发 > IOS开发

iOS 定义View任意角为圆角

2016-03-17 17:53 465 查看
在开发过程中,经常会遇到过圆角的控件,如头像,按钮,这一类的需求一般都是定义4个角都是圆角,只需定义它图层的圆角度就行
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


以上方法很简单,方便,但是,我在开发过程中遇到了一种蛋疼的问题,cell的上面2个角为直角,下面2个角为圆角,找了很多方法都不行,最后查资料发现了下面的方法

+ (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) 是设置圆角的程度
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: