我有从touchesBegan和touchesMoved点创建的UIBezierPath数组。 我想在屏幕上为它们绘制动画。
如果不迭代每个bezier并调用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()
}
答案 0 :(得分:2)
您最好的选择是使用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")