最近做的项目中,有个设置用户头像为圆角的需求。如果使用
imageView.layer.masksToBounds = YES;
imageView.layer.cornerRadius = 5.0f;
的方法设置圆角图片,会对应用的性能造成影响,如果tabelview中有较多的圆角图片,则会造成tableview拖动卡顿的问题
网上搜索资料找到替代的解决方法如下:(使用贝塞尔曲线代替之)
+ (UIImage *)circleImageWithBorder:(CGFloat)borderW color:(UIColor *)boderColor image:(UIImage *)oriImage {
// 计算新图片的大小
CGSize size = CGSizeMake(oriImage.size.width + 2 * borderW, oriImage.size.height + 2 * borderW);
// 开始位图上下文(大小、原始图片的宽高+2*边框宽度)
UIGraphicsBeginImageContext(size);
// 绘制大圆边框
UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, 0, size.width, size.height)];
[boderColor set];
[path fill];
// 绘制小圆(把小圆设置成剪裁区域)
UIBezierPath *clipPath = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(borderW, borderW, oriImage.size.width, oriImage.size.height)];
[clipPath addClip];
// 把图片绘制到上下文中
[oriImage drawAtPoint:CGPointMake(borderW, borderW)];
// 从上下文中生成图片
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
// 关闭上下文
UIGraphicsEndImageContext();
return newImage;
}
效果如下: