在另一个问题中,如何回答动画: Draw line animated
然后我尝试同时添加一个动画视图。我想创建两个动画路径,它们在同一CGPoint
会面,但有不同的路径到达那里。我希望两个路径同时启动并同时结束动画。我目前的方法是创建第二个UIBezierPath
名为path2,以及第二个CAShapeLayer
名为shapeLayer2
,但第二个路径只是覆盖第一个路径。我非常确定两条路径都需要不同的CAShapeLayer
,因为每条路径都有不同的属性。我似乎需要将CAShapeLayer
实例添加为view.layer
子图层,但它似乎无法正常工作。为了达到预期的效果,我应该做些什么?
答案 0 :(得分:0)
这是最终奏效的。
func animatePath() {
// create whatever path you want
let path = UIBezierPath()
path.move(to: CGPoint(x: 10, y: 100))
path.addLine(to: CGPoint(x: 200, y: 50))
path.addLine(to: CGPoint(x: 200, y: 240))
// create whatever path you want
let path2 = UIBezierPath()
let bottomStartX = view.frame.maxX - 10
let bottomStartY = view.frame.maxY - 100
path2.move(to: CGPoint(x: bottomStartX, y: bottomStartY))
path2.addLine(to: CGPoint(x: bottomStartX - 100, y: bottomStartY - 100))
path2.addLine(to: CGPoint(x: 200, y: 240))
// create shape layer for that path
let shapeLayer = CAShapeLayer()
shapeLayer.fillColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 0).cgColor
shapeLayer.strokeColor = #colorLiteral(red: 1, green: 0, blue: 0, alpha: 1).cgColor
shapeLayer.lineWidth = 4
shapeLayer.path = path.cgPath
let shapeLayer2 = CAShapeLayer()
shapeLayer2.fillColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 0).cgColor
shapeLayer2.strokeColor = UIColor.blue.cgColor
shapeLayer2.lineWidth = 4
shapeLayer2.path = path.cgPath
// animate it
view.layer.addSublayer(shapeLayer)
view.layer.addSublayer(shapeLayer2)
let animation = CABasicAnimation(keyPath: "strokeEnd")
animation.fromValue = 0
animation.duration = 2
shapeLayer.add(animation, forKey: "MyAnimation")
let animation2 = CABasicAnimation(keyPath: "strokeEnd")
animation2.fromValue = 0
animation2.duration = 2
shapeLayer2.add(animation2, forKey: "MyAnimation")
// save shape layer
self.shapeLayer = shapeLayer
}