延迟CABasicAnimation立即绘制它

时间:2019-03-21 18:59:19

标签: ios swift xcode cabasicanimation

我正在尝试对多条分裂的线进行动画处理。它们将具有可变数量的拆分,但是我试图使下一个拆分仅在上一个拆分完成之后才开始。所有的分割都是在线段的末尾与下一段的开始之间的小间隙。同样,我最终将使每个片段花费特定的时间来完成,但是我无法延迟动画,因此可以将它们链接在一起。

我使用Advanced Animation Tricks作为参考,但是每当我打开视图控制器(调用该动画存储在其中的函数)时,所有的线段都将立即绘制而没有动画或延迟,我也不知道为什么正在发生。

这里是我的动画处理过程:

for i in 0...(splits.count - 1)
{
    //create path
    //start buffered after split
    //finish buffered before split
    let path1 = UIBezierPath()
    path1.move(to: CGPoint(x: lineSplits[i] + 5, y: lineLoc[0] - CGFloat(lw/2)))
    path1.addLine(to: CGPoint(x: lineSplits[i] + 5, y: lineLoc[0] - CGFloat(lw/2)))
    path1.addLine(to: CGPoint(x: lineSplits[i + 1] - 5, y: lineLoc[0] - CGFloat(lw/2)))

    let path2 = UIBezierPath()
    path2.move(to: CGPoint(x: lineSplits[i] + 5, y: lineLoc[0] + CGFloat(lw/2)))
    path2.addLine(to: CGPoint(x: lineSplits[i] + 5, y: lineLoc[0] + CGFloat(lw/2)))
    path2.addLine(to: CGPoint(x: lineSplits[i + 1] - 5, y: lineLoc[0] + CGFloat(lw/2)))

    // create shape layer for that path
    let shapeLayer1 = CAShapeLayer()
    shapeLayer1.fillColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 0).cgColor
    shapeLayer1.strokeColor = #colorLiteral(red: 0.8078431487, green: 0.02745098062, blue: 0.3333333433, alpha: 1).cgColor
    shapeLayer1.lineWidth = CGFloat(lw)
    shapeLayer1.path = path1.cgPath

    let shapeLayer2 = CAShapeLayer()
    shapeLayer2.fillColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 0).cgColor
    shapeLayer2.strokeColor = #colorLiteral(red: 0.2196078449, green: 0.007843137719, blue: 0.8549019694, alpha: 1).cgColor
    shapeLayer2.lineWidth = CGFloat(lw)
    shapeLayer2.path = path2.cgPath

    // animate it with a delay
    let currentLayerTime1 = shapeLayer1.convertTime(CACurrentMediaTime(), from: nil)
    let currentLayerTime2 = shapeLayer2.convertTime(CACurrentMediaTime(), from: nil)

    view.layer.addSublayer(shapeLayer1)
    let animation = CABasicAnimation(keyPath: "strokeEnd")
    animation.beginTime = currentLayerTime1 + 5
    animation.duration = 5
    animation.fillMode = CAMediaTimingFillMode.backwards
    shapeLayer1.add(animation, forKey: "MyAnimation")


    view.layer.addSublayer(shapeLayer2)
    let animation2 = CABasicAnimation(keyPath: "strokeEnd")
    //animation2.fromValue = 0
    animation2.beginTime = currentLayerTime2 + 10
    animation2.duration = 10
    animation2.fillMode = CAMediaTimingFillMode.backwards
    shapeLayer2.add(animation2, forKey: "MyAnimation")
}

1 个答案:

答案 0 :(得分:0)

尝试将antimation.beginTime替换为:

animation.beginTime = CACurrentMediaTime() + 5

代替您使用的currentLayerTime1