iOS 定义View任意角为圆角

在开发过程中,经常会遇到过圆角的控件,如头像,按钮,这一类的需求一般都是定义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) 是设置圆角的程度


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值