简体   繁体   English

如何以编程方式同时为两个视图同时设置动画?

[英]How do I animate two views simultaneously in swift programmatically?

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. 我想创建两个动画路径,这些路径在相同的CGPoint处相遇,但有不同的路径到达那里。 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. 我当前的方法是创建第二个UIBezierPath称为path2,以及第二个CAShapeLayer名为shapeLayer2 ,但是第二个路径只是覆盖第一个路径。 I'm pretty sure both paths need different CAShapeLayer s because each path will have different attributes. 我很确定两个路径都需要不同的CAShapeLayer因为每个路径将具有不同的属性。 It seems like I then need to add the CAShapeLayer instance as a view.layer sublayer but it doesn't seem to be working. 似乎然后我需要将CAShapeLayer实例添加为view.layer子层,但它似乎无法正常工作。 What should I be doing differently to achieve the desired result? 为了达到预期的效果,我应该做些什么?

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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM