面试宝点iOS开发-小技能

10. 如何高性能的给UIImageView加个圆角?

2016-09-02  本文已影响1276人  IreneWu

日常我们使用layer的两个属性,简单的两行代码就能实现圆角的呈现

imageView.layer.cornerRadius = CGFloat(10); 
imageView.layer.masksToBounds = YES;

由于这样处理的渲染机制是GPU在当前屏幕缓冲区外新开辟一个渲染缓冲区进行工作,也就是离屏渲染,这会给我们带来额外的性能损耗,如果这样的圆角操作达到一定数量,会触发缓冲区的频繁合并和上下文的的频繁切换,性能的代价会宏观地表现在用户体验上----掉帧。
会引发离屏渲染的操作:

The following will trigger offscreen rendering:
Any layer with a mask (layer.mask)
Any layer with layer.masksToBounds / view.clipsToBounds being true
Any layer with layer.allowsGroupOpacity set to YES and layer.opacity is less than 1.0
Any layer with a drop shadow (layer.shadow*).
Any layer with layer.shouldRasterize being true
Any layer with layer.cornerRadius, layer.edgeAntialiasingMask, layer.allowsEdgeAntialiasing
Text (any kind, including UILabel, CATextLayer, Core Text, etc).
Most of the drawing you do with CGContext in drawRect:. Even an empty implementation will be rendered offscreen.

因为这些效果均被认为不能直接呈现于屏幕,而需要在别的地方做额外的处理预合成。具体的检测我们可以使用Instruments的CoreAnimation。

不用layer.cornerRadius:

/** * @brief clip the cornerRadius with image, UIImageView must be setFrame before, no off-screen-rendered */
- (void)zy_cornerRadiusWithImage:(UIImage *)image cornerRadius:(CGFloat)cornerRadius rectCornerType:(UIRectCorner)rectCornerType { 
    CGSize size = self.bounds.size; 
    CGFloat scale = [UIScreen mainScreen].scale; 
    CGSize cornerRadii = CGSizeMake(cornerRadius, cornerRadius);     
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ 
        UIGraphicsBeginImageContextWithOptions(size, YES, scale); 
        if (nil == UIGraphicsGetCurrentContext()) { 
            return; 
        } 
        UIBezierPath *cornerPath = [UIBezierPath bezierPathWithRoundedRect:self.bounds byRoundingCorners:rectCornerType cornerRadii:cornerRadii]; 
        [cornerPath addClip]; 
        [image drawInRect:self.bounds]; 
        id processedImageRef = (__bridge id _Nullable)(UIGraphicsGetImageFromCurrentImageContext().CGImage); 
        UIGraphicsEndImageContext(); 
        dispatch_async(dispatch_get_main_queue(), ^{ 
            self.layer.contents = processedImageRef; 
        }); 
    });
}

对图片进行了切角处理后,将得到的含圆角UIImage通过-setImage传给了UIImageView。操作没有触发GPU离屏渲染,过程在CPU内完成。
顺便一提这里还存在一个性能问题,Color Blended Layers
,UIGraphicsBeginImageContextWithOptions(<#CGSize size#>, <#BOOL opaque#>, <#CGFloat scale#>)
的第二个参数是透明通道的开关,true则为不透明。以下两张图是参数传NO or YES在模拟器中打开了Color Blended Layers Debug所看见的区别:


7ECF802F-7C88-46ED-9E81-0650841EDB01.png

一些没有被设置为opacity的图层,因为透明通道的存在,系统需要去计算图层堆叠后像素点的真实颜色,在Instruments的测试中也是可以高亮标显出来,这种性能的损耗程度我还没有专门去测试。但是在上图可以看见如果设置为不包含透明通道,我们图片被剪去的部分就没有了颜色(黑漆漆一片),这里使用的解决方案就是在图片上下文中先画一层backgroundColor,缺点就是需要传入:

/** * @brief clip the cornerRadius with image, draw the backgroundColor you want, UIImageView must be setFrame before, no off-screen-rendered */
- (void)zy_cornerRadiusWithImage:(UIImage *)image cornerRadius:(CGFloat)cornerRadius rectCornerType:(UIRectCorner)rectCornerType backgroundColor:(UIColor *)backgroundColor { 
    CGSize size = self.bounds.size; 
    CGFloat scale = [UIScreen mainScreen].scale; 
    CGSize cornerRadii = CGSizeMake(cornerRadius, cornerRadius);     
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ 
        UIGraphicsBeginImageContextWithOptions(size, YES, scale); 
        if (nil == UIGraphicsGetCurrentContext()) { 
            return; 
        } 
        UIBezierPath *cornerPath = [UIBezierPath bezierPathWithRoundedRect:self.bounds byRoundingCorners:rectCornerType cornerRadii:cornerRadii]; 
        UIBezierPath *backgroundRect = [UIBezierPath bezierPathWithRect:self.bounds];   
        [backgroundColor setFill]; 
        [backgroundRect fill]; 
        [cornerPath addClip]; 
        [image drawInRect:self.bounds]; 
        id processedImageRef = (__bridge id _Nullable)(UIGraphicsGetImageFromCurrentImageContext().CGImage); 
        UIGraphicsEndImageContext(); 
        dispatch_async(dispatch_get_main_queue(), ^{ 
            self.layer.contents = processedImageRef; 
        }); 
    });
}

整理来源:ZYCornerRadius

上一篇下一篇

猜你喜欢

热点阅读