使用贝塞尔曲线设置圆角

最终效果图:
使用贝塞尔曲线设置圆角_第1张图片

近日在项目中遇到一个问题,UIButton需要设置border,同时设置其中三个角为圆角,第四个角为直角,于是第一次我的代码是这样的

[self.btnContent setBackgroundColor:[UIColor clearColor]];
self.btnContent.layer.borderWidth = 1;
self.btnContent.layer.borderColor =RGBCOLOR(123, 184, 255).CGColor;
UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:rect  byRoundingCorners:(UIRectCornerTopLeft|UIRectCornerTopRight|UIRectCornerBottomLeft)  cornerRadii:CGSizeMake(5, 5)];
CAShapeLayer *maskLayer = [CAShapeLayer layer];
maskLayer.path = maskPath.CGPath;
self.btnContent.layer.mask = maskLayer;

结果就是直线部分有边框,但是设置圆角的部分边线被贝塞尔曲线切掉,后来在网上找个一个方法,在button上覆盖一个有边框的UIView:

UIView *strokeView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.btnContent.width, self.btnContent.height)];
[self.btnContent addSubview:strokeView];

CAShapeLayer *strokeLayer = [CAShapeLayer layer];
strokeLayer.path = maskPath.CGPath;
strokeLayer.fillColor = [UIColor clearColor].CGColor; //内容填充的颜色设置为clear
strokeLayer.strokeColor = RGBCOLOR(123, 184, 255).CGColor; //边色
strokeLayer.lineWidth = 1; // 边宽
[strokeView.layer addSublayer:strokeLayer];

这样的确可以解决问题,但是代码太过复杂,后来研究发现,在button的layer上添加一个layer,同样可以解决问题

[self.btnContent setBackgroundColor:[UIColor clearColor]];
CAShapeLayer *maskLayer = [CAShapeLayer layer];
CGRect rect = CGRectMake(1, 1, self.btnContent.width-2, self.btnContent.height-2);

UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:rect  byRoundingCorners:(UIRectCornerTopLeft|UIRectCornerTopRight|UIRectCornerBottomLeft)  cornerRadii:CGSizeMake(5, 5)];
maskLayer.path = maskPath.CGPath;
maskLayer.fillColor = [UIColor clearColor].CGColor; //内容填充的颜色设置为clear
maskLayer.strokeColor = RGBCOLOR(123, 184, 255).CGColor; //边色
maskLayer.lineWidth = 1.0f;
maskLayer.frame = CGRectMake(0, 0, CGRectGetWidth(rect), CGRectGetHeight(rect));
[self.btnContent.layer addSublayer:maskLayer];
//*这里注意是lineWidth,区别于borderWidth

你可能感兴趣的:(iOS)