我试图在 0.1 秒的动画 block 中将 NSImageView 缩放/调整为原始大小的 120%,然后在动画 block 完成后返回到原始大小。执行此操作最快且占用 CPU 最少的方法是什么?
我基本上是在寻找与 iOS 中使用的以下代码等效的代码,但我需要它用于 Mac 应用程序:
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration: 0.1];
image.transform = CGAffineTransformScale(image.transform, newSize, newSize);
[UIView setAnimationDelegate:self];
[UIView commitAnimations];
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration: 0.1];
image.transform = CGAffineTransformScale(image.transform, originalSize, originalSize);
[UIView setAnimationDelegate:self];
[UIView commitAnimations];
感谢您的帮助。
最佳答案
它可能会占用一些 CPU,具体取决于图像是否在 NSImageView
内部缩放,但您可以使用 NSAnimationContext
完成同样的事情,如下所示:
NSRect oldFrame = self.imageView.frame;
NSRect newFrame = NSMakeRect(self.imageView.frame.origin.x,
self.imageView.frame.origin.y,
self.imageView.frame.size.width*1.2f,
self.imageView.frame.size.height*1.2f);
[NSAnimationContext runAnimationGroup:^(NSAnimationContext *context){
// Animating to the new frame...
[context setDuration:0.1f];
[[self.imageView animator] setFrame:newFrame];
} completionHandler:^{
[NSAnimationContext runAnimationGroup:^(NSAnimationContext *context){
// Back to the old frame...
[context setDuration:0.1f];
[[self.imageView animator] setFrame:oldFrame];
} completionHandler:nil];
}];
但这种方式适用于 OS X 10.7 及更高版本。
这也可以通过看起来有点像 UIView
代码的方式完成,并且适用于 10.5 及更高版本:
- (void)whatever {
NSRect oldFrame = self.imageView.frame;
NSRect newFrame = NSMakeRect(self.imageView.frame.origin.x,
self.imageView.frame.origin.y,
self.imageView.frame.size.width*1.2f,
self.imageView.frame.size.height*1.2f);
[self performSelector:@selector(animateImageViewToFrame:)
withObject:[NSValue valueWithRect:newFrame]
afterDelay:0];
[self performSelector:@selector(animateImageViewToFrame:)
withObject:[NSValue valueWithRect:oldFrame]
afterDelay:0.1f];
}
- (void)animateImageViewToFrame:(NSValue*)frameValue {
[NSAnimationContext beginGrouping];
[[NSAnimationContext currentContext] setDuration:0.1f];
// Get smaller
[[self.imageView animator] setFrame:[frameValue rectValue]];
[NSAnimationContext endGrouping];
}
当然,如果这能奏效那就太棒了:
[NSAnimationContext beginGrouping];
[[NSAnimationContext currentContext] setDuration:0.1f];
[[self.imageView animator] setFrame:newFrame];
[NSAnimationContext endGrouping];
[NSAnimationContext beginGrouping];
[[NSAnimationContext currentContext] setDuration:0.1f];
[[self.imageView animator] setFrame:oldFrame];
[NSAnimationContext endGrouping];
或者更好:
[NSAnimationContext beginGrouping];
[[NSAnimationContext currentContext] setDuration:0.1f];
[[self.imageView animator] setFrame:newFrame];
[[self.imageView animator] setFrame:oldFrame];
[NSAnimationContext endGrouping];
但由于我无法弄清楚的原因,这些都没有做任何事情。
参见 NSAnimationContext Class Reference了解更多信息。
关于objective-c - 动画调整 NSImageView 大小的最有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15723434/