14

I just rewrote quite a big animation from a dumb while loop (firing drawRect: x times) and this is the last thing that I just can't figure out..

How can I get the current elapsed time of my animation? I know how to get the current CFTimeInterval (Is there a way to pause a CABasicAnimation?):

CFTimeInterval currentTime = [self.multiplierLayer convertTime:CACurrentMediaTime() fromLayer:nil];

But how can I use this to calculate the current elapsed time from the moment my animation started? It seems that beginTime is always 0.0, do I have to set that the moment my animation starts and then extract the currentTime from the beginTime?

I'm sorry if it's something simple that I'm overlooking, I just started using Core Animation yesterday. :)

Edit: Setting beginTime is not the way to do it, really at a loss here.

Community
  • 1
  • 1
Rick van der Linde
  • 2,581
  • 1
  • 20
  • 22
  • Why can't you simply record the current time when the animation started (which you know as you had to start it)? – trojanfoe Feb 24 '13 at 09:00
  • 1
    or be the delegate and check in `animationDidStart:` – David Rönnqvist Feb 24 '13 at 09:04
  • So combined; record the current time inside `animationDidStart:`. Yes that would work nice for a single animation, but what about multiple animations? Just track them all? It would be a shame if there is no other way to get the elapsed time from an animation. – Rick van der Linde Feb 24 '13 at 09:10
  • 3
    You record the value **in** the CALayer itself using a `NSNumber` object and `setValue:forKey:`. – trojanfoe Feb 24 '13 at 09:32
  • Ah! I need to go out for a bit now, will try this when I get back. When it works (it will), could you submit it as the answer so I can check it? – Rick van der Linde Feb 24 '13 at 12:40
  • 2
    Totally forgot to come back here, sorry. Could you add your answer as an answer so I can give you the credits? I got it to work :) – Rick van der Linde Feb 28 '13 at 21:43

1 Answers1

10

A possibly easier way to do what you want is when you create your CABasicAnimation explicitly set the starting time, like:

basicAnimation.beginTime = CACurrentMediaTime();

Later on you can figure out how much time has elapsed with:

CFTimeInterval elapsedTime = CACurrentMediaTime() - basicAnimation.beginTime;

And get the percentage through with:

progress = elapsedTime / basicAnimation.duration;

(The code will be slightly more complex if you have a timeOffset or something like that.)

Wil Shipley
  • 9,343
  • 35
  • 59