iOS 列表性能优化思路

一 原理
CoreAnimation 有一个基础的渲染 pipeline:


Tile Based Rendering.png

数据的基本流向是: Application(CoreAnimation) -> RenderServer(CPU, CoreAnimation, OpenGL, Metal) —> pipeline(GPU, Tiler, Renderer -> Render Buffer)

二 问题定位
在出现图像性能问题,滑动,动画不够流畅之后,我们首先要做的就是定位出问题的所在. 就需要能有脉络的分析可能产生问题的环节:
1 定位帧率, 先使用 FPSLabel 显示一下帧率, 看看是否在 58-60 之间. (Instruments 中检测的数据更准确);
2 定位瓶颈, 确定是 CPU 还是 GPU. 希望 CPU 和 GPU 的占有率越少越好;
3 检查是否做了不必要的 CPU 渲染, 比如重写了 -drawRect() 方法, 引起了 CPU 的离屏渲染, 理想情况是让 GPU 负责更多的渲染工作;
4 检查是否有过多的 GPU 离屏渲染, 离屏渲染会有上下文切换和额外的缓存空间消耗;
5 检查是否有过多的 blending, 过多的 blending 需要更多的 GPU 资源;
6 检查图片格式是否为常用格式, 比如 png, jpeg, 是否字节对齐, 是否开启了 alpha 通道, 图片来源是否是 asset(静态)
7 检查是否有过多的 view 或者 效果, 比如实现毛玻璃效果等;
8 检查 view 层级中是否有不正确的部分, 是否有过多的对 view 的操作比如重绘, 布局等, 如果出现约束报错, 需要修改;

三 离屏渲染
1 为 UIView, UIImageView 高效添加圆角

(1) 使用 UIGraphicsBeginImageContextWithOptions:
使用 CoreGraph 为 UIView 直接绘制圆角

let circleSize = CGSize(width: 60, height: 60)

UIGraphicsBeginImageContextWithOptions(circleSize, true, 0)

// Draw a circle
let ctx = UIGraphicsGetCurrentContext()!
UIColor.red.setFill()
ctx.setFillColor(UIColor.red.cgColor)
ctx.addEllipse(in: CGRect(x: 0, y: 0, width: circleSize.width, height: circleSize.height))
ctx.drawPath(using: .fill)

let circleImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()

为 UIImageView 添加圆角:
直接截取图片, 使用贝塞尔曲线绘制圆角路径

extension UIImage {  
    func drawRectWithRoundedCorner(radius radius: CGFloat, _ sizetoFit: CGSize) -> UIImage {
        let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: sizetoFit)

        UIGraphicsBeginImageContextWithOptions(rect.size, false, UIScreen.mainScreen().scale)
        CGContextAddPath(UIGraphicsGetCurrentContext(),
            UIBezierPath(roundedRect: rect, byRoundingCorners: UIRectCorner.AllCorners,
                cornerRadii: CGSize(width: radius, height: radius)).CGPath)
        CGContextClip(UIGraphicsGetCurrentContext())
        // CPU offscreen render
        self.drawInRect(rect)
        CGContextDrawPath(UIGraphicsGetCurrentContext(), .FillStroke)
        let output = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();

        return output
    }
}

(2) 使用贝塞尔曲线

// be careful
- (void)drawRect:(CGRect)rect {
  CGRect bounds = self.bounds;
  [[UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:8.0] addClip];

  [self.image drawInRect:bounds];
}

(3) iOS 12 开始官方推荐使用 UIGraphicsImageRenderer() --> 能节省高达 75% 的内存, 支持 iOS 10+;

let circleSize = CGSize(width: 60, height: 60)
let renderer = UIGraphicsImageRenderer(bounds: CGRect(x: 0, y: 0, width: circleSize.width, height: circleSize.height))

let circleImage = renderer.image{ ctx in
    UIColor.red.setFill()
    ctx.cgContext.setFillColor(UIColor.red.cgColor)
    ctx.cgContext.addEllipse(in: CGRect(x: 0, y: 0, width: circleSize.width, height: circleSize.height))
    ctx.cgContext.drawPath(using: .fill)
}

四 另一个内存使用大户
将图片解码到内存中(Data buffers -> Image buffers), 会需要很多的内存空间. 其大小与原始图像大小成比例, 和 View 的大小无关.
使用缩略图的形式降低内存使用

func downsample(imageAt imageURL: URL, to pointSize: CGSize, scale: CGFloat) -> UIImage {

    // 生成CGImageSourceRef 时,不需要先解码。
    let imageSourceOptions = [kCGImageSourceShouldCache: false] as CFDictionary
    let imageSource = CGImageSourceCreateWithURL(imageURL as CFURL, imageSourceOptions)!
    let maxDimensionInPixels = max(pointSize.width, pointSize.height) * scale
    
    // kCGImageSourceShouldCacheImmediately 
    // 在创建Thumbnail时直接解码,这样就把解码的时机控制在这个downsample的函数内
    let downsampleOptions = [kCGImageSourceCreateThumbnailFromImageAlways: true,
                                 kCGImageSourceShouldCacheImmediately: true,
                                 kCGImageSourceCreateThumbnailWithTransform: true,
                                 kCGImageSourceThumbnailMaxPixelSize: maxDimensionInPixels] as CFDictionary
    // 生成
    let downsampledImage = CGImageSourceCreateThumbnailAtIndex(imageSource, 0, downsampleOptions)!
    return UIImage(cgImage: downsampledImage)
}

解码同样会耗费大量的 CPU 资源。如果用户快速滑动界面,很有可能因为解码而造成卡顿。
解决方法:
使用 iOS 10+ 的 Prefetching 和 后台解码

五 SDWebImage/KingFisher 中是怎么做图片解码的
SDWebImage 之前使用的是 UIGraphicsBeginImageContextWithOptions 进行解码.
编解码部分还有好多东西要学, SDWebImage 的源码分析文章:
SDWebImage 源码分析: Decoder

你可能感兴趣的:(iOS 列表性能优化思路)