在 CABasicAnimation 中向前跳转 (iOS)

Skip forward in CABasicAnimation (iOS)

我目前有一个用作视频进度指示器的动画,效果很好。但是,现在我们有一个功能,允许用户通过点击它向前跳 2.5 秒进入视频,因此我正在尝试实现进度指示器动画以向前跳 2.5 秒进入动画。我如何将动画向前跳过 2.5 秒?我已经尝试 "animationGroup.timeOffset = 2.5" 但它不起作用。

func performProgressIndicatorAnimation(duration: Float64) {
    layer.mask = nil
    layer.speed = 1.0

    self.duration = duration
    let strokeStartAnimation = CABasicAnimation(keyPath: "strokeStart")
    strokeStartAnimation.fromValue = 0
    strokeStartAnimation.toValue = 1
    strokeStartAnimation.duration = duration
    strokeStartAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)

    animationGroup = CAAnimationGroup()
    animationGroup.duration = duration
    animationGroup.animations = [strokeStartAnimation]
    externalCircle.addAnimation(animationGroup, forKey: "animationGroup")

}

//这里是我绘制的外部圆圈:

private func drawCircles() {

    let externalCirclePath = UIBezierPath(roundedRect: CGRectMake(0, 0, bounds.height, bounds.height), cornerRadius: bounds.height / 2)
    externalCircle.path = externalCirclePath.CGPath
    externalCircle.fillColor = UIColor.clearColor().CGColor
    externalCircle.strokeColor = UIColor.whiteColor().CGColor
    externalCircle.lineWidth = 2

    let internalCircleRadius = bounds.size.height / 5
    let internalCirclePath = UIBezierPath(roundedRect: CGRectMake(0, 0, internalCircleRadius * 2, internalCircleRadius * 2), cornerRadius: internalCircleRadius)
    internalCircle.path = internalCirclePath.CGPath
    internalCircle.fillColor = UIColor.whiteColor().CGColor
    internalCircle.position = CGPointMake(CGRectGetMidX(bounds) - internalCircleRadius,
                                          CGRectGetMidY(bounds) - internalCircleRadius);

    layer.addSublayer(internalCircle)
    layer.addSublayer(externalCircle)
}

通过删除之前的动画并根据经过的百分比(带跳过)启动它来做到这一点

func skipProgressIndicatorAnimation(currentTime: CMTime, timeToSkip: Double, duration: CMTime) {

    animationGroup = nil
    externalCircle.removeAllAnimations()

    let percentageElapsedWithSkip = (CMTimeGetSeconds(currentTime) + timeToSkip) / CMTimeGetSeconds(duration)

    let strokeStartAnimation = CABasicAnimation(keyPath: "strokeStart")
    strokeStartAnimation.fromValue = percentageElapsedWithSkip
    strokeStartAnimation.toValue = 1
    strokeStartAnimation.duration = CMTimeGetSeconds(duration) - CMTimeGetSeconds(currentTime) - timeToSkip
    strokeStartAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)

    animationGroup = CAAnimationGroup()
    animationGroup.duration = CMTimeGetSeconds(duration) - CMTimeGetSeconds(currentTime) - timeToSkip
    animationGroup.animations = [strokeStartAnimation]
    externalCircle.addAnimation(animationGroup, forKey: "animationGroup")

}

如果您使用 timeOffset 跳过一部分动画,它仍将播放相同的总时长。动画简单地循环并再次播放,直到它最初开始的地方。 例如:动画:A->B->C。如果您使用 timeOffSet 以便从 B 开始,它将是:B->C->A

在这种情况下,我想你可以关闭这个动画,然后添加新的。