Search code examples
iosswiftcore-animation

Starting animation at a given offset


Is there a way to achieve what the timeOffset property of an animation does, starting the animation at some point in time, but without the "wrapping" behaviour?

I have two animations (in two different layers):

// This is the animation of the stroke of a circle
let progressAnim = CABasicAnimation(keyPath: "strokeEnd")
progressAnim.duration = duration
progressAnim.fromValue = 0
progressAnim.toValue = 1
progressAnim.fillMode = kCAFillModeBackwards
progressAnim.timeOffset = elapsed

// This is the animation of a pointer that follow the same circle as above
let arrowAnim = CAKeyframeAnimation(keyPath: "position")
arrowAnim.duration = duration
arrowAnim.rotationMode = kCAAnimationRotateAuto
arrowAnim.path = arrowPath.CGPath
arrowAnim.fillMode = kCAFillModeBackwards
arrowAnim.timeOffset = elapsed

This starts the animations at the wanted progress, but when it reaches what is supposed to the the end, it starts over and lasts for the remaining duration. I realize this is how timeOffset is specified to work, but I was hoping that it is possible to somehow achieve the same without the wrap.


Solution

  • I think I figured it out. By trial and error, it seems to work when I set beginTime of the animation to a time in the past, like this:

    let beginTime = CACurrentMediaTime() - offset
    // Set the beginTime of the progress animation
    progressAnim.beginTime = beginTime
    // Set the begintTime of the arrow animation
    arrowAnim.beginTime = beginTime
    

    This seems to have the desired effect.