CAShapeLayer 和drawRect 繪制圖形的區(qū)別

一般都是使用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)的曲線

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容