美文网首页aa雨下思考
图片圆角提升性能

图片圆角提升性能

作者: 方克己 | 来源:发表于2016-02-26 16:03 被阅读247次

    这样就可以减少很多性能开支

    Objective - C

    - (UIImage *)hyb_imageWithCornerRadius:(CGFloat)radius {
      CGRect rect = (CGRect){0.f, 0.f, self.size};
      
      UIGraphicsBeginImageContextWithOptions(self.size, NO, UIScreen.mainScreen.scale);
      CGContextAddPath(UIGraphicsGetCurrentContext(),
                       [UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:radius].CGPath);
      CGContextClip(UIGraphicsGetCurrentContext());
      
      [self drawInRect:rect];
      UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
      
      UIGraphicsEndImageContext();
      
      return image;
    }
    

    swift 版

    //MARK:- 设置图片圆角
        func setImageCornerRadius(radius:CGFloat) -> UIImage{
            
            let rect = CGRectMake(0, 0, self.size.width, self.size.height)
            UIGraphicsBeginImageContextWithOptions(self.size, false, UIScreen.mainScreen().scale)
            CGContextAddPath(UIGraphicsGetCurrentContext(), UIBezierPath(roundedRect: rect, cornerRadius: radius).CGPath)
            CGContextClip(UIGraphicsGetCurrentContext())
            self.drawInRect(rect)
            let image = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndPDFContext()
            
            return image
        }
    

    还有一种方法就是

    imgView.layer.cornerRadius = 10;
    // 这一行代码是很消耗性能的
    imgView.clipsToBounds = YES;
    

    好处是使用简单,操作方便。坏处是离屏渲染(off-screen-rendering)需要消耗性能。对于图片比较多的视图上,不建议使用这种方法来设置圆角。通常来说,计算机系统中CPU、GPU、显示器是协同工作的。CPU计算好显示内容提交到GPU,GPU渲染完成后将渲染结果放入帧缓冲区。

    简单来说,离屏渲染,导致本该GPU干的活,结果交给了CPU来干,而CPU又不擅长GPU干的活,于是拖慢了UI层的FPS(数据帧率),并且离屏需要创建新的缓冲区和上下文切换,因此消耗较大的性能。

    相关文章

      网友评论

      • adrian920:据说ios9开始uiimageview用png图片的时候,圆角就是on-screen-rendering。
      • GaryChow:方法一还是离屏渲染啊。

      本文标题:图片圆角提升性能

      本文链接:https://www.haomeiwen.com/subject/mvhikttx.html