CAShapeLayer 和drawRect 繪制圖形的區別

一般都是使用CAShapeLayer 繪制圖形, 今天突然看到使用 drawRect 繪制圖片, 在想兩個異同點. 為什么shapeLayer 會成為主流的結合貝塞爾曲線繪制圖形

  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來渲染圖形, 節省性能. 動畫渲染直接交給手機GPU, 不消耗內存

CAShapeLayer 與 UIBezierPath的關系

CAShapeLayer 中的shaper代表形狀, 所以需要形狀才能生效
貝塞爾曲線可以創建基于矢量的路徑, 而 UIBezierPath類 是對 CGPathRef的封裝, 貝塞爾曲線 給CAShapeLayer提供路徑, CAShapeLayer 在提供的路徑中進行渲染, 路徑會閉環, 所以繪制除了shape
用于CAShapeLayer的貝塞爾曲線作為path,其path是一個首尾相接的閉環的曲線,即使該貝塞爾曲線不是一個閉環的曲線

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容