iOS常用组件之高效切圆角的方法汇总

2020-01-21 03:56:31王振洲

UIImageView

UIImageView 有四种方式实现圆角:

截取图片方式(性能较好,基本不掉帧)


@implementation UIImage (extend)
- (UIImage *)drawRectWithRoundedCorner
{
 CGRect rect = CGRectMake(0.f, 0.f, 150.f, 150.f); 
 UIBezierPath *bezierPath = [UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:rect.size.width * 0.5];
 UIGraphicsBeginImageContextWithOptions(rect.size, false, [UIScreen mainScreen].scale);
 CGContextAddPath(UIGraphicsGetCurrentContext(), bezierPath.CGPath);
 CGContextClip(UIGraphicsGetCurrentContext());
 [self drawInRect:rect];
 CGContextDrawPath(UIGraphicsGetCurrentContext(), kCGPathFillStroke);
 UIImage *output = UIGraphicsGetImageFromCurrentImageContext();
 UIGraphicsEndImageContext(); 
 return output;
}
@end

贝塞尔曲线切割圆角(不推荐,掉帧严重)


- (UIImageView *)roundedRectImageViewWithCornerRadius:(CGFloat)cornerRadius {
 UIBezierPath *bezierPath = [UIBezierPath bezierPathWithRoundedRect:self.bounds cornerRadius:cornerRadius];
 CAShapeLayer *layer = [CAShapeLayer layer];
 layer.path = bezierPath.CGPath;
 self.layer.mask = layer;
 return self;
}

绘制四个角的遮罩(使用场景受限)

在 UIImageView 上添加一个四个角有内容,其它部分是透明的视图,只对 UIImageView 圆角部分进行遮挡。但要保证被遮挡的部分背景色要与周围背景相同,避免穿帮。所以当 UIImageView 处于一个复杂的背景时,是不适合使用这个方法的。

最不推荐做法(当一个页面只有少量圆角图片时才推荐使用)


UIImageView *imageView = [[UIImageView alloc] init];
imageView.layer.cornerRadius = 5.f;
imageView.layer.masksToBounds = YES;

总结

以上是开发过程常用组件的切圆角方法总结,如果有更好的方法或者文中有不对的地方,还请指正提出,谢谢。

好了,以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对ASPKU的支持。


注:相关教程知识阅读请移步到IOS开发频道。