iOS:关于UIView切角的两种实现方式

转载自:http://www.jianshu.com/p/451b7fa94e2a

 

第一种: 我想你一见到代码,就瞬间有吐的冲动,最常用的一种方式。。。

UIButton *button = [[UIButton alloc]init];
button.frame = CGRectMake(100, 100, 100, 40);
button.backgroundColor = [UIColor redColor];
button.layer.cornerRadius = 20.0f;
button.layer.masksToBounds = YES;
[button setTitle:
@"测试" forState:UIControlStateNormal]; [self.view addSubview:button];

如此简单...但是,它默认强制裁掉了四个角啊。。。那问题来了,假如需求只要求切一个角呢。。。看第二种方法

第二种: 还是在layer上做文章,不同采用的是类扩展的方法,接下来以UIButton为例,具体效果看下图:

#import "UIButton+Corner.h"

@implementation UIButton (Corner)

- (void)corner
{
    CGRect bounds = self.bounds;
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:bounds byRoundingCorners:UIRectCornerBottomLeft cornerRadii:CGSizeMake(20, 20)];
    CAShapeLayer *maskLayer = [CAShapeLayer layer];
    maskLayer.frame = bounds;
    maskLayer.path = maskPath.CGPath;
    [self.layer addSublayer:maskLayer];
    self.layer.mask = maskLayer;
}
@end

从上不难看出代码关键所在...这里只做简单的扩展...具体根据项目需求来
再次列出官方裁边的可选项

typedef NS_OPTIONS(NSUInteger, UIRectCorner) {
    UIRectCornerTopLeft     = 1 << 0,
    UIRectCornerTopRight    = 1 << 1,
    UIRectCornerBottomLeft  = 1 << 2,
    UIRectCornerBottomRight = 1 << 3,
    UIRectCornerAllCorners  = ~0UL
};

 

原文地址:https://www.cnblogs.com/XYQ-208910/p/5198209.html