I have a NSWindow containing a NSView with ‘Wants Core Animation Layer’ enabled. The view then contains many NSImageView that use are initially animated into position. When I run the animation, it is extremely sluggish and drops most of the frames. However, if I disable ‘Wants Core Animation Layer’ the animation works perfectly. I’m going to need the core animation layer but can’t figure out how to get it to perform adequately.
Can I do anything to fix the performance issues?
Here is the code:
// AppDelegate
NSRect origin = ...;
NSTimeInterval d = 0.0;
for (id view in views)
{
[view performSelector:@selector(animateFrom:) withObject:origin afterDelay:d];
d += 0.05f;
}
// NSImageView+Animations
- (void)animateFrom:(NSRect)origin
{
NSRect original = self.frame;
[self setFrame:origin];
[NSAnimationContext beginGrouping];
[[NSAnimationContext currentContext] setDuration:0.20f];
[[self animator] setFrame:original];
[NSAnimationContext endGrouping];
}
It’s possible that the
NSTimeris killing your performance. Core Animation has rich support for controlling the timing of animations through theCAMediaTimingprotocol, and you should take advantage of that in your app. Instead of using the animator proxy andNSAnimationContext, try using Core Animation directly. If you create aCABasicAnimationfor each image and set itsbeginTime, it will delay the start of the animation. Also, for the delay to work the way you want, you must wrap each animation in aCAAnimationGroupwith itsdurationset to the total time of the entire animation.Using the
frameproperty could also be contributing to the slowdown. I really like to take advantage of thetransformproperty onCALayerin situations like this where you’re doing an “opening” animation. You can lay out your images in IB (or in code) at their final positions, and right before the window becomes visible, modify their transforms to the animation’s starting position. Then, you just reset all of the transforms toCATransform3DIdentityto get the interface into its normal state.I have an example in my <plug type=”shameless”> upcoming Core Animation book </plug> that’s very similar to what you’re trying to do. It animates 30
NSImageViews simultaneously with no dropped frames. I modified the example for you and put it up on github. These are the most relevant bits of code with the extraneous UI stuff stripped out:Transform the layers to their start position
Animate the transform back to the identity
I also have a video on YouTube of the example in action if you want to check it out.