【问题标题】:Is CABasicAnimation practice different for UI objects and CALayers?UI 对象和 CALayers 的 CABasicAnimation 实践是否不同?
【发布时间】:2014-01-21 05:28:52
【问题描述】:

我只是想知道这是否是使用 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"];

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

【问题讨论】:

  • serveBlock2 是一个 CALayer。 [gameTypeControl layer] 是一个 CALayer。例子都是一样的。

标签: ios core-animation calayer cabasicanimation


【解决方案1】:

问题在于,如果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!表示层和模型层自动知道旧值和新值。

【讨论】:

  • 您好,您能否详细说明如何从上面的示例中的表示层和模型层自动知道旧值和新值?如果我理解正确:通过使用setDisableAction:YES,我们可以防止c 被隐式设置动画,因此在您调用CABasicAnimation 之前不会发生转换,对吗?谢谢。
  • 动画发生在很晚,在当前 CATransaction 结束之后。
  • @Unheilig 转换(或任何其他更改)现在发生。但是用户看不到它,因为表示层直到动画开始才开始移动,而动画开始的时间更晚。请参阅my explanation 了解动画何时运行以及它是如何工作的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多