如何在NSImageView中为内容开关设置动画?

Ale*_*ers 6 macos cocoa animation nsimageview

我想切换一个显示的图像NSImageView,但我想动画那个变化.我尝试过各种方法来做到这一点.希望你们其中一个人可以建议一个可能真正起作用的人.我正在使用Cocoa for Mac.

Nic*_*ley 7

据我所知,NSImageView不支持动画图像更改.但是,您可以NSImageView在第一个上面放置一秒,然后隐藏旧的并显示新的动画.例如:

NSImageView *newImageView = [[NSImageView alloc] initWithFrame: [imageView frame]];
[newImageView setImageFrameStyle: [imageView imageFrameStyle]];
// anything else you need to copy properties from the old image view
// ...or unarchive it from a nib

[newImageView setImage: [NSImage imageNamed: @"NSAdvanced"]];
[[imageView superview] addSubview: newImageView
                       positioned: NSWindowAbove relativeTo: imageView];
[newImageView release];

NSDictionary *fadeIn = [NSDictionary dictionaryWithObjectsAndKeys:
             newImageView, NSViewAnimationTargetKey,
             NSViewAnimationFadeInEffect, NSViewAnimationEffectKey,
             nil];
NSDictionary *fadeOut = [NSDictionary dictionaryWithObjectsAndKeys:
             imageView, NSViewAnimationTargetKey,
             NSViewAnimationFadeOutEffect, NSViewAnimationEffectKey,
             nil];
NSViewAnimation *animation = [[NSViewAnimation alloc] initWithViewAnimations:
              [NSArray arrayWithObjects: fadeOut, fadeIn, nil]];
[animation setAnimationBlockingMode: NSAnimationBlocking];
[animation setDuration: 2.0];
[animation setAnimationCurve: NSAnimationEaseInOut];
[animation startAnimation];
[imageView removeFromSuperview];
imageView = newImageView;
[animation release];
Run Code Online (Sandbox Code Playgroud)

如果您的视图很大并且您可以要求10.5+,那么您可以使用Core Animation执行相同的操作,这将是硬件加速并且使用更少的CPU.

创建newImageView后,执行以下操作:

[newImageView setAlphaValue: 0];
[newImageView setWantsLayer: YES];
// ...
[self performSelector: @selector(animateNewImageView:) withObject: newImageView afterDelay: 0];

- (void)animateNewImageView:(NSImageView *)newImageView;
{
    [NSAnimationContext beginGrouping];
    [[NSAnimationContext currentContext] setDuration: 2];
    [[newImageView animator] setAlphaValue: 1];
    [[imageView animator] setAlphaValue: 0];
    [NSAnimationContext endGrouping];
}
Run Code Online (Sandbox Code Playgroud)

你需要修改上面的内容才能生成,但我不打算为你编写所有代码:-)


Rob*_*ger 5

您可以实现自己的自定义视图,该视图使用Core Animation CALayer来存储图像.设置contents图层的属性时,图像将自动从旧图像平滑地动画到新图像.

  • 听起来不错.但是我怎么做呢? (2认同)