修改圆角个数

前言:

我们在开发中经常会遇到将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属性是切除多余的。
如果有疑问或者更好的修改圆角个数的方式,欢迎联系!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值