带着问题我们来探讨一下:
1.设置圆角一定会触发离屏渲染么?
会不会不妨一试。打开xcode,打开模拟器离屏渲染颜色标记
设置btn:背景色+圆角
@IBOutlet weak var btn: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
btn.layer.cornerRadius = 100
btn.backgroundColor = .blue
btn.layer.borderColor = UIColor.black.cgColor
btn.layer.borderWidth = 5.0
}
然后我们改下btn的设置:添加图片+圆角(图片并非自带圆角)
btn.layer.cornerRadius = 100
btn.backgroundColor = .blue
btn.setImage(UIImage(named: "1.jpg"), for: .normal)
btn.layer.borderColor = UIColor.black.cgColor
btn.layer.borderWidth = 5.0
Setting the radius to a value greater than 0.0 causes the layer to begin drawing rounded corners on its background. 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.
原来如此,cornerRadius只会默认设置background color 和 border of the layer,不会设置content。除非设置layer.masksToBounds或view的clipsToBounds. 那就来呗:
btn.layer.masksToBounds = true
走你!
那离屏渲染的始作俑者也就找到了!那为什么一句裁剪就会触发呢?
离屏渲染的真正原因:
这要从图层的绘制机制说起。图层的绘制大致遵循“画家算法”:画家算法也叫作优先填充,它是三维计算机图形学中处理可见性问题的一种解决方法。由远及近的绘制,较近的场景覆盖较远的。
在正常情况下,绘制完成后就可以提交frameBuffer进行显示,当我们设置了圆角+裁剪后,绘制完成的sublayer因为还要被剪裁,所以第一次绘制完成后并不能被丢弃,而是被保存在了offScreen buffer中,因此引发了离屏渲染。。。
总结:
能触发离屏渲染的方式有很多:mask,投影,光栅化等,所以我们在开发中还需多留意。