UIKit 性能调优
https://bestswifter.com/uikitxing-neng-diao-you-shi-zhan-jiang-jie/
避免图层混合
- 确保控件的 opaque(不透明) 属性为 true
- 确保 backgroundColor 和父视图颜色一致且不透明
- 如无特殊需要, 不要设置低于1的 alpha 值
- 确保 UIImage 没有 alpha 通道
避免临时转换
- 确保图片大小和 frame 一致, 不要在滑动时缩放图片
- 确保图片颜色格式被 GPU 支持, 避免 CPU 频繁转换
慎用离屏渲染
- 绝大多数时候离屏渲染会影响性能
- 重写 drawRect 方法, 设置圆角, 阴影, 模糊效果, 光栅化都会导致离屏渲染
- 设置阴影效果是加上阴影路径
- 滑动时若需要圆角效果, 开启光栅
设置 cornerRadius 本身不会导致离屏渲染, 但是很多时候它还需要配合 layer.masksToBounds = true 使用, 设置 masksToBounds 会导致离屏渲染.所以在尽可能在滑动的界面避免设置圆角, 如果必须设置圆角, 可以使用光栅化技术将圆角缓存起来
// 设置圆角
label.layer.masksToBounds = true
label.layer.cornerRadius = 8
label.layer.shouldRasterize = true
label.layer.rasterizationScale = layer.contentScale
iOS高效添加圆角效果实战讲解
https://bestswifter.com/efficient-rounded-corner/
- 如果能够只用 cornerRadius 解决问题, 就不用优化
- 如果必须设置 masksToBounds, 可以参考圆角的数量, 如果数量较少(一页只有几个)也可以考虑不用优化
By default, the corner radius does not apply to the image in the layer’s contents property; it applies only to the background color and border of the layer. However, setting the masksToBounds property to true causes the content to be clipped to the rounded corners.
默认情况下, 这个属性只会影响视图的背景颜色和 border. 对于 UILabel 这样内部还有子视图的控件就无能为力了.所以很多情况我们会看到这样的代码:
label.layer.cornerRadius = 5
label.layer.masksToBounds = true
- UIImageView 的圆角通过直接截取图片实现, 其他视图的圆角可以通过 Core Graphics 画出圆角矩形实现