Question

I've just started playing with NSAnimation and Core Animation, but I can't seem to animate a NSImage sliding in from offscreen (I also can't get a rotating animation to work, but that's a different question). When I initialize the NSImageView (with the NSImage set to its image property) outside of the window no image is displayed. What exactly am I doing wrong to cause the NSImage to not redraw?

imageView = [[NSImageView alloc] initWithFrame:NSMakeRect(-818, 0, 818, 494)];
NSImage *image = [NSImage imageNamed:@"image.png"];

[imageView setImage:image];

[mainView addSubview:imageView];

NSRect outFrame = NSMakeRect(678, 0, imageView.frame.size.width, imageView.frame.size.width);

CABasicAnimation *animation = [CABasicAnimation animation];
animation.toValue = [NSValue valueWithRect:outFrame];


NSView *view = self.window.contentView;
view.animations = @{@"frame" : animation};
[[view animator] setFrame:outFrame];
Was it helpful?

Solution

Your code is confused.

You first need to turn on layer backing of your view.

Then you either want to use an animation proxy to change the property you want to animate, OR you want to use a CAAnimation to animate it's layer, not both.

For simply animating it's position, using an animation proxy is simpler.

I mostly write for iOS these days, so I've barely used animation proxies.

I believe you should be able to just get rid of your CAAnimation and your code that sets the frame on the animation proxy should work. You need to set the flag to make your view layer-backed in order for this to work however.

add this code after adding your view to its superview:

imageView.wantsLayer = YES;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top