2011-07-18 86 views
3

这是我的代码片断为可可应用程序使用核心动画,不知何故动画不显示。动画不显示

CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"position"]; 
[animation setDelegate:self]; 

NSRect pos = [imageView frame]; 
[animation setFromValue:[NSValue valueWithRect:pos]]; 
NSPoint point = NSMakePoint(pos.origin.x-40, pos.origin.y); 

[animation setToValue:[NSValue valueWithPoint:point]]; 
[animation setDuration:2.0]; 

[[imageView animator] addAnimation:animation forKey:@"myTest"]; 

,而这是工作代码:

NSRect position = [imageView frame]; 
position.origin.x -= 40; 
[[imageView animator] setFrame:position]; 

但自动翻转不起作用。

第一个有问题吗?以及如何使第二个反向运动工作?谢谢!

回答

0

我不确定,但对于第一个,位置是一个CGPoint,因此您可以尝试将这种类型用于fromValue和toValue。你目前正在使用一个NSRect和一个NSPoint(后者应该可以工作,但不知道前者)。

第二,你如何指定自动反转? + setAnimationRepeatAutoreverses需要从动画块内部调用(在“beginAnimations”之后)

0

(注意:我对Cocoa不是很有经验,因为我主要是iOS开发人员;我还没有测试任何以下的东西)

我认为问题是你想混合CoreAnimation和Animator代理。你不动画添加到动画,但该层:

[[imageView layer] addAnimation:animation forKey:@"myTest"]; 

另一种可能性可能是使用NSViewAnimation并把它们连在一起。请参阅第13页上的Animation Programming Guide for Cocoa。因此,您将有一个动画朝一个方向前进,一旦完成,将触发第二个返回的动画。看起来这工作:

NSMutableDictionary *firstDict = [NSMutableDictionary dictionary]; 
[firstDict setObject:imageView forKey:NSViewAnimationTargetKey]; 
[firstDict setObject:[NSValue valueWithRect:originalFrame] forKey:NSViewAnimationStartFrameKey]; 
[firstDict setObject:[NSValue valueWithRect:targetFrame] forKey:NSViewAnimationEndFrameKey]; 

NSMutableDictionary *secondDict = [NSMutableDictionary dictionary]; 
[secondDict setObject:imageView forKey:NSViewAnimationTargetKey]; 
[secondDict setObject:[NSValue valueWithRect:targetFrame] forKey:NSViewAnimationStartFrameKey]; 
[secondDict setObject:[NSValue valueWithRect:originalFrame] forKey:NSViewAnimationEndFrameKey]; 

NSViewAnimation *firstAnimation = [[NSViewAnimation alloc] initWithViewAnimations:[NSArray arrayWithObject:firstDict]]; 
[firstAnimation setDuration:2.0]; 

NSViewAnimation *secondAnimation = [[NSViewAnimation alloc] initWithViewAnimations:[NSArray arrayWithObject:secondDict]]; 
[secondAnimation setDuration:2.0]; 

[secondAnimation startWhenAnimation:firstAnimation reachesProgress:1.0]; 
[firstAnimation startAnimation]; 

然后,在狮子(OS X 10.7),你可以设置一个completion handler when using Animator Proxy。它应该像这样工作:

[NSAnimationContext beginGrouping]; 
[[NSAnimationContext currentContext] setDuration:2.0]; 
[[NSAnimationContext currentContext] setCompletionHandler:^(void) { 
    // Here comes your code for the reverse animation. 
    [NSAnimationContext beginGrouping]; 
    [[NSAnimationContext currentContext] setDuration:2.0]; 
    [[aView animator] setFrameOrigin:originalPosition]; 
    [NSAnimationContext endGrouping]; 
}]; 
[[aView animator] setFrameOrigin:position]; 
[NSAnimationContext endGrouping];