CABasicAnimation current elapsed time

2019-04-20 15:01发布

问题:

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.

回答1:

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.)