对于UI对象和CALayers,CABasicAnimation实践是否不同?

时间:2014-01-21 05:28:53

标签: ios core-animation calayer cabasicanimation

我只是想知道这是否是使用CABasicAnimation为CALayer设置动画的正确方法。

关于Stack Overflow我已经学会了如何通过在运行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"];

这是对的吗?我这样做了吗?

1 个答案:

答案 0 :(得分: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!从表示层和模型层自动知道旧值和新值。