【问题标题】:How do I animate two views simultaneously in swift programmatically?如何以编程方式快速同时为两个视图设置动画?
【发布时间】:2018-03-31 23:22:43
【问题描述】:

在另一个问题中,回答了如何制作动画: Draw line animated

然后我尝试添加一个视图以同时进行动画处理。我想创建两条动画路径,它们在同一 CGPoint 处相遇,但到达那里的路径不同。我希望两条路径同时开始并同时结束动画。我目前的方法是创建第二个UIBezierPath,称为path2,以及第二个CAShapeLayer,称为shapeLayer2,但第二个路径只是覆盖第一个。我很确定两条路径都需要不同的CAShapeLayers,因为每条路径都有不同的属性。似乎我需要将CAShapeLayer 实例添加为view.layer 子层,但它似乎不起作用。为了达到预期的结果,我应该做些什么不同的事情?

【问题讨论】:

  • 对于shapeLayer2,您需要第二个CABasicAnimation(keyPath: "strokeEnd")
  • 好的,我加了。它的动画正确但没有显示红色路径。就像我添加子图层时,它会覆盖第一个。
  • 没关系,我明白了。我给第二个形状层提供了与第一个相同的路径。我将其更新为 path2。
  • 如果这能解决你的问题,我建议你删除这个问题...
  • 是的,我知道这会让人感到困惑。我可以看到这对处于我这种情况的人很有用。我将发布代码作为答案。如果您仍然认为我应该在那之后删除它,请告诉我。

标签: swift animation


【解决方案1】:

这就是最终奏效的方法。

    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
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-03-12
    • 1970-01-01
    • 1970-01-01
    • 2020-09-24
    • 1970-01-01
    • 1970-01-01
    • 2017-03-31
    • 2016-07-27
    相关资源
    最近更新 更多