我有从 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")
关于ios - UIBezierPath数组动画绘制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43930104/