IOS开发性能优化之设置圆角图片
2016-12-17 本文已影响185人
搬运工开发者
1、使用cornerRadius,比较耗性能
imageView.layer.cornerRadius = 10;
imageView.layer.masksToBounds = YES;
此方法比较耗性能,如果勾选Color OffSreen-Rendered 会发现imageView的死角出现黄色的标记,就是出现离屏渲染。
如果不设置 imageView.layer.masksToBounds = YES;会出现图层混合。勾选Color Blended Layer就会发现图片上显示红色,就是出现图层混合。
如图所示:


触发离屏渲染Offscreen rendering的行为:
(1)drawRect:方法
(2)layer.shadow
(3)layer.allowsGroupOpacity or layer.allowsEdgeAntialiasing
(4)layer.shouldRasterize
(5)layer.mask
(6)layer.masksToBounds && layer.cornerRadius
2、使用CAShapeLayer和UIBezierPath
//width控件宽度、height控件高度
CGRect rect = CGRectMake(0, 0, width, height);
CGSize cornerRadio = CGSizeMake(radio, radio);
UIRectCorner corner = UIRectCornerAllCorners;
UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:rect byRoundingCorners:corner cornerRadii:cornerRadio];
CAShapeLayer *masklayer = [[CAShapeLayer alloc] init];
masklayer.frame = rect;
masklayer.path = path.CGPath;
self.layer.mask = masklayer;
这一种情况也出现了离屏渲染,从性能上讲这一种比第一种消耗的性能更少。

3、生成以上带有圆角的图片
/**
绘制图片
@param size 规定绘制而成的图片大小
@param fillColor 背景颜色
@param cornerRadio 圆角大小
@param completion 完成回调
*/
- (void)my_ImageWithSize:(CGSize)size fillColor:(UIColor *)fillColor cornerRadio:(CGFloat)cornerRadio completion:(void (^)(UIImage *))completion{
dispatch_async(dispatch_get_global_queue(0, 0), ^{
UIGraphicsBeginImageContextWithOptions(size, YES, [UIScreen mainScreen].scale);
CGSize aspectFitSize = size;
CGRect rect = CGRectMake(0, 0, aspectFitSize.width+0.3, aspectFitSize.height+0.3);
[fillColor setFill];
UIRectFill(rect);
if (cornerRadio != 0) {
UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0, aspectFitSize.width, aspectFitSize.height) byRoundingCorners:UIRectCornerAllCorners cornerRadii:CGSizeMake(10, 10)];
[path addClip];
}
[self drawInRect:rect];
UIImage *result = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
dispatch_async(dispatch_get_main_queue(), ^{
if (completion != nil) {
if (result) {
completion(result);
}
}
});
});
}
__weak typeof(self) weakSelf = self;
UIImage *image = [UIImage imageNamed:@"tupian.jpg"];
[image my_ImageWithSize:self.imageViewThree.frame.size fillColor:[UIColor whiteColor] cornerRadio:10.0 completion:^(UIImage *image) {
weakSelf.imageViewThree.image = image;
}];
使用这一种就不会出现离屏幕渲染,推荐使用这种方法。
这种方法主要是根据图片重新生成一张新的图片,这里其实并没有设置imageVIew圆角,只是生成的图片四个顶点有部分跟imageView的superView同样的背景颜色。
