Ryan
Ryan

Reputation: 545

Synchronizing CAAnimations

I have a repeating animation that I need to synchronize with some other transient animations. The repeating animation is a scan line that moves across the screen for 4s. As it passes over images underneath, those images need to "blip."

The blipping images can come and go and move at the whim of the user. They are also not part of the same layer.

I can't figure out how to keep the scan line and the image animations in sync. I would consider adding them all to a CAAnimationGroup, but the "animations" property is a readonly NSArray, so it seems like I'd have to re-create the group every time one of the blipping animations is added, removed, or moves, which will be fairly often. I'm also guessing that creating a new group would mean the scan line animation would need to be restarted, causing it to be jerky.

According to this post:

=">CAAnimation that calls a method in periodic animation-progress intervals?

Core Animation is "time-based," but I'm not sure I fully understand what that means for a repeating animation and how reliable it is (I can't find this mentioned in any of the online documentation). Does that mean if I start the scan line repeating animation at time x, it will repeat at exact 4s intervals after it's been started? What about the app going to the background and returning or similar?

Thanks for your help!

Ryan

Upvotes: 4

Views: 788

Answers (1)

Ryan
Ryan

Reputation: 545

After fiddling with this for a bit, I found that I could synchronize my animations by making sure their beginTimes lined up. I started by setting the beginTime of the scan line animation:

scanAnimation.beginTime = CACurrentMediaTime();

From there I simply computed the offset within the 4s window (call it dt) and set the other animations' beginTimes to that:

blipAnimation.beginTime = scanAnimation.beginTime + dt;

This worked perfectly even if the beginTime was in the past; the animation engine actually extrapolated forward and animated the next blip dt seconds after the scan animation looped back.

The downside is that I've now absolutely bludgeoned the frame rate. I'm trying to find useful information about Core Animation performance, but so far to no avail. I've taken a pretty simple approach to laying out all of my images and animations so far and I'm prepared to rewrite a lot of code to optimize it, but I don't want to embark on a rewrite without some preparation. Any pointers to in-depth discussions about how Core Animation works would be really handy.

Upvotes: 4

Related Questions