How do I animate two views simultaneously in swift

2019-08-17 01:39发布

问题:

In another question, how to animate was answered: Draw line animated

I then tried to add a view to animate simultaneously. I want to create two animated paths that meet at the same CGPoint but have different paths to get there. I want both paths to start at the same time and end animation at the same time. My current approach is to create a second UIBezierPath called path2, along with a second CAShapeLayer called shapeLayer2, but the second path is just overriding the first. I'm pretty sure both paths need different CAShapeLayers because each path will have different attributes. It seems like I then need to add the CAShapeLayer instance as a view.layer sublayer but it doesn't seem to be working. What should I be doing differently to achieve the desired result?

回答1:

Here is what ultimately worked.

    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
}