2014-01-21 33 views
0

我只是想知道这是否是用CABasicAnimation动画CALayer的正确方法。对于UI对象和CALayers,CABasicAnimation练习是否有所不同?

在堆栈溢出我已经学会了如何通过运行一个CABasicAnimation之前设置一个新的位置,以动画UI对象:

动画UI目标实例

gameTypeControl.center = CGPointMake(gameTypeControl.center.x, -slidingUpValue/2); 
CABasicAnimation *removeGameTypeControl = [CABasicAnimation animationWithKeyPath:@"transform.translation.y"]; 
[removeGameTypeControl setFromValue:[NSNumber numberWithFloat:slidingUpValue]]; 
[removeGameTypeControl setToValue:[NSNumber numberWithFloat:0]]; 
[removeGameTypeControl setDuration:1.0]; 
[removeGameTypeControl setTimingFunction:[CAMediaTimingFunction functionWithControlPoints:0.8 :-0.8 :1.0 :1.0]]; 
[[gameTypeControl layer] addAnimation:removeGameTypeControl forKey:@"removeGameTypeControl"]; 

现在我已经试过这个方法在CALayer上,但它似乎工作不同。对我来说,得到相同的结果。我已经将ToValue设置为新的y位置,而不是像使用UI对象动画一样使用值0。

动画一个CALayer的实例

serveBlock2.position = CGPointMake((screenBounds.size.height/4)*3, -screenBounds.size.width/2); 
CABasicAnimation *updateCurrentServe2 = [CABasicAnimation animationWithKeyPath:@"position.y"]; 
updateCurrentServe2.fromValue = [NSNumber numberWithFloat:slidingUpValue/2]; 
[updateCurrentServe2 setToValue:[NSNumber numberWithFloat:-screenBounds.size.width/2]]; 
[updateCurrentServe2 setDuration:1.0]; 
[serveBlock2 addAnimation:updateCurrentServe2 forKey:@"serveBlock2 updateCurrentServe2"]; 

这是正确的吗?我做对了吗?

+0

'serveBlock2'是一个CALayer。 '[gameTypeControl层]'是一个CALayer。这些例子是一样的。 – matt

回答

0

问题是,如果serveBlock2不是视图的直接底层,那么在第二个示例的第一行中设置其position将启动不同的动画(隐式动画)。防止这种情况的方法是关闭隐式动画。因此,这个例子from my book

CompassLayer* c = (CompassLayer*)self.compass.layer; 
[CATransaction setDisableActions:YES]; // <=== this is important 
c.arrow.transform = CATransform3DRotate(c.arrow.transform, M_PI/4.0, 0, 0, 1); 
CABasicAnimation* anim = [CABasicAnimation animationWithKeyPath:@"transform"]; 
anim.duration = 0.8; 
[c.arrow addAnimation:anim forKey:nil]; 

这样,我不必有fromValuetoValue!表示层和模型层自动识别旧值和新值。

+0

您好,请您详细说明一下在上面的示例中,如何自动从表示层和模型层中知道旧值和新值?如果我理解正确:通过使用'setDisableAction:YES',我们可以防止'c'被隐式地动画化,所以直到你调用'CABasicAnimation',变换才会发生,我正确吗?谢谢。 – Unheilig

+0

动画发生在当前CATransaction结束之后。 – matt

+0

@Unheilig变换(或任何其他变化)现在发生。但是用户没有看到它,因为表示层直到动画开始才开始移动,这是晚些时候。请参阅动画运行时的[我的解释](http://www.apeth.com/iOSBook/ch17.html#_drawing_animation_and_threading)以及它如何工作。 – matt

相关问题