一般都是使用CAShapeLayer 繪制圖形, 今天突然看到使用 drawRect 繪制圖片, 在想兩個(gè)異同點(diǎn). 為什么shapeLayer 會成為主流的結(jié)合貝塞爾曲線繪制圖形
override func draw(in ctx: CGContext) {
let red = UIColor.red
red.set()
//繪制矩形
let rectPath = UIBezierPath(rect: CGRect(x: position.x - 30, y: position.y - 30, width: 60, height: 60))
ctx.addPath(rectPath.cgPath)
ctx.setStrokeColor(UIColor.orange.cgColor)
ctx.setLineWidth(1.0)
ctx.strokePath()
let shapeLayer = CAShapeLayer()
shapeLayer.frame = CGRect(x: 0, y: 0, width: frame.size.width, height: frame.size.height)
shapeLayer.path = rectPath.cgPath
shapeLayer.strokeColor = UIColor.red.cgColor
shapeLayer.lineWidth = 2
self.addSublayer(shapeLayer)
}
drawRect: 屬于 CoreGraphics框架, 占用CPU, 性能消耗大
CAShapeLayer : 屬于 CoreAnimation 框架, 通過GPU來渲染圖形, 節(jié)省性能. 動(dòng)畫渲染直接交給手機(jī)GPU, 不消耗內(nèi)存
CAShapeLayer 與 UIBezierPath的關(guān)系
CAShapeLayer 中的shaper代表形狀, 所以需要形狀才能生效
貝塞爾曲線可以創(chuàng)建基于矢量的路徑, 而 UIBezierPath類 是對 CGPathRef的封裝, 貝塞爾曲線 給CAShapeLayer提供路徑, CAShapeLayer 在提供的路徑中進(jìn)行渲染, 路徑會閉環(huán), 所以繪制除了shape
用于CAShapeLayer的貝塞爾曲線作為path,其path是一個(gè)首尾相接的閉環(huán)的曲線,即使該貝塞爾曲線不是一個(gè)閉環(huán)的曲線