关于UIView切圆角的两种方式

在 iOS App 开发中,切圆角的场景有很多。
很多图片或者 UIView 都需要切圆角。
关于UIView切圆角的两种方式
文章图片
很多场景都需要切 UIView 的圆角 切圆角的方式一般有两种。 第一种,使用 UIView 内嵌的 layer,直接来切圆角,方便快捷。

UIImageView *userHeaderImgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"header"]]; userHeaderImgView.layer.cornerRadius = 39; userHeaderImgView.layer.masksToBounds = YES;

这样做的好处:方便快捷,2个属性就能搞定 UIView 的圆角切割。
这样做的坏处:切的圆角会产生混合图层,影响效率。
关于UIView切圆角的两种方式
文章图片
直接使用 UIView.layer 的方式切圆角会有混的图层 【关于UIView切圆角的两种方式】第二种,使用 CAShaperLayer 搭配 UIBezierPath 路径设置切割路径,然后把 layer 设置到 UIView 的 mask 属性上。
UIImageView *userHeaderImgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"header"]]; dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ CAShapeLayer *cornerLayer = [CAShapeLayer layer]; UIBezierPath *cornerPath = [UIBezierPath bezierPathWithRoundedRect:userHeaderImgView.bounds cornerRadius:39]; cornerLayer.path = cornerPath.CGPath; cornerLayer.frame = userHeaderImgView.bounds; userHeaderImgView.layer.mask = cornerLayer; });

这样做的好处:切割的圆角不会产生混合图层,提高效率。
这样做的坏处:代码量偏多,且很多 UIView 都是使用约束布局,必须搭配 dispatch_after 函数来设置自身的 mask。因为只有在此时,才能把 UIView 的正确的 bounds 设置到 CAShapeLayer 的 frame 上。
关于UIView切圆角的两种方式
文章图片
使用 CAShapeLayer 搭配 UIBezierPath 可以避免混合图层![![15253982594372.jpg](https://upload-images.jianshu.io/upload_images/2701794-eb126e8e69253795.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ](https://upload-images.jianshu.io/upload_images/2701794-7a657b30afe942a3.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 使用 CAShapeLayer 切圆角还有另外一个好处。
常规的使用 UIView.layer.cornerRadius & UIView.layer.masksToBounds 虽然方便,但有一点是无法避免的。
那就是:它会把四个角都给切了。没有办法精确的控制切哪一个或者多个角。
可以使用 CAShapeLayer 搭配 UIBezierPathUIRectCorner 参数
+ (instancetype)bezierPathWithRoundedRect:(CGRect)rect byRoundingCorners:(UIRectCorner)corners cornerRadii:(CGSize)cornerRadii;

来决定UIView 的4个叫,切哪几个或者是都切了。

    推荐阅读