UIBezierPath数组动画绘制

Animated drawing of UIBezierPath array

我有从 touchesBegan 和 touchesMoved 点创建的 UIBezierPath 数组。 我想在屏幕上绘制动画。

不迭代每个贝塞尔曲线并调用 setNeedsDisplay() 的最佳方法是什么?

谢谢

  override func draw(_ rect: CGRect) {
      for bezier in beziers{
         bezier.stroke()
      }
   }
   override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
      super.touchesBegan(touches, with: event)
      let cgPoint = touches.first!.location(in: self)
      let bezierPath = ColorBezierPath() // subclass of UIBezierPath
      bezierPath.lineWidth = lineWidth
      bezierPath.color = color
      bezierPath.move(to: cgPoint)
      beziers.append(bezierPath)
   }

   override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
      super.touchesMoved(touches, with: event)
      let cgPoint = touches.first!.location(in: self)
      let bezierPath = beziers.last
      bezierPath?.addLine(to: cgPoint)
      setNeedsDisplay()
   }

您最好的选择是使用 CAShapeLayer。它需要一条路径和各种其他设置。要为其设置动画,只需将其 strokeEnd 属性 从 0.0 设置为 1.0。给定您想要的任何动画时间参数,这将创建从头到尾绘制路径的效果:

let shapeLayer = CAShapeLayer()               // strokeEnd's model value is 1.0 by default
shapeLayer.frame = containerLayer.bounds
shapeLayer.path = bezierPath.cgPath
containerLayer.addSublayer(shapeLayer)

let strokeEndAnimation = CABasicAnimation(keyPath: "strokeEnd")
strokeEndAnimation.duration = 2.0
strokeEndAnimation.fromValue = 0.0

shapeLayer.add(strokeEndAnimation, forKey: "strokeEndAnimation")