在Apple官方文档中多次提出开发时,避免触发离屏渲染效果.离屏渲染触发的情况有很多种,具体可参考iOS离屏渲染相关探索,本文主要讲圆角的性能优化
离屏渲染的触发情况
- 使用mask的 layer (layer.mask)
- 需要进行裁剪的layer(layer.masksToBounds / view.clipsToBounds)
- 设置了组透明度为 YES,并且透明度不为 1 的 layer (layer.allowsGroupOpacity/ layer.opacity)
- 添加了投影的layer(layer.shadow)
- 采用了 光栅化的layer(layer.shouldRasterize)
- 绘制了文字的layer(UILabel, CATextLayer, Core Text 等)
方案一
img.layer.cornerRadius = 50;
img.layer.masksToBounds = YES;
设置 border/backgroundColor的情况下不推荐,触发离屏渲染
方案二
//贝塞尔曲线
- (UIImage *)rounderCornerImageWithCornerRadius:(CGFloat)cornerRadius
{
int w = self.size.width * self.scale;
int h = self.size.height * self.scale;
CGRect rect = CGRectMake(0, 0, w, h);
//使用贝塞尔
UIGraphicsBeginImageContextWithOptions(CGSizeMake(w, h), false, 1.0);
[[UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:c] addClip];
[self drawInRect:rect];
UIImage *ret = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return ret;
}
方案三
UIImageView *imageView = [[UIImageViewalloc] initWithFrame:CGRectMake(100,100,100,100)];
imageView.image = [UIImage imageNamed:@"myImg"];
UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:imageView.boundsbyRoundingCorners:UIRectCornerAllCornerscornerRadii:imageView.bounds.size];
CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
//设置大小
maskLayer.frame = imageView.bounds;
//设置图形样子
maskLayer.path = maskPath.CGPath;
imageView.layer.mask = maskLayer;
[self.view addSubview:imageView];
用CAShapeLayer的内存消耗少,渲染速度快
方案四
圆形图片设置图叠加遮罩









网友评论