2010-12-09 45 views
5

现在有谁能够使用CAKeyframeAnimation同时动画多个图层吗? 每个图层都有自己的CAKeyframeAnimation对象。看一看代码如下:多个CAKeyframeAnimation同时在不同的图层中

我具有接收的对象的方法,创建CAKeyframeAnimation并附加动画它:

- (void)animateMovingObject:(CALayer*)obj 
       fromPosition:(CGPoint)startPosition 
       toPosition:(CGPoint)endPosition 
        duration:(NSTimeInterval)duration { 
    CAKeyframeAnimation *pathAnimation = [CAKeyframeAnimation animationWithKeyPath:@"position"]; 
    pathAnimation.calculationMode = kCAAnimationPaced; 
    //pathAnimation.fillMode = kkCAFillModeRemoved; // default 
    //pathAnimation.removedOnCompletion = YES; // default 
    pathAnimation.duration = duration; 

    // create an empty mutable path 
    CGMutablePathRef curvedPath = CGPathCreateMutable(); 

    // set the starting point of the path 
    CGPathMoveToPoint(curvedPath, NULL, startPosition.x, startPosition.y); 

    CGPathAddCurveToPoint(curvedPath, NULL, 
          startPosition.x, endPosition.y, 
          startPosition.x, endPosition.y, 
          endPosition.x, endPosition.y); 
    pathAnimation.path = curvedPath; 
    [obj addAnimation:pathAnimation forKey:@"pathAnimation"]; 
    CGPathRelease(curvedPath); 
} 

现在,假设我有3层加入作为在一个子层我的棋盘游戏,我提出以下电话:

CALayer obj1 = ... // set up layer and add as sublayer 
[self animateMovingObject:obj1 
      fromPosition:CGPointMake(0.0, 0.0) 
       toPosition:CGPointMake(100.0, 100.0) 
       duration:2.0]; 

CALayer obj2 = ... // set up layer and add as sublayer 
[self animateMovingObject:obj2 
      fromPosition:CGPointMake(0.0, 0.0) 
       toPosition:CGPointMake(150.0, 100.0) 
       duration:2.0]; 

CALayer obj3 = ... // set up layer and add as sublayer 
[self animateMovingObject:obj3 
      fromPosition:CGPointMake(0.0, 0.0) 
       toPosition:CGPointMake(200.0, 100.0) 
       duration:2.0]; 

通过这样做,我只能看到obj3正在从位置(0.0,0.0)迁(200.0,100.0)。 我错过了什么?我应该使用NSOperationQueue/Threads吗? 使用CAKeyframeAnimation的animationDidStart:委托方法在此上下文中似乎没有用处。

任何想法?

在此先感谢。

回答

4

如果你想将一系列这样的动画,让他们保证是同步的,你可以将它们包装在一个CATransaction:

[CATransaction begin]; 
[CATransaction setValue:[NSNumber numberWithFloat:2.0] forKey:kCATransactionAnimationDuration];  

// Do animations 

[CATransaction commit];  

但是,我不太知道为什么即使没有同步,您编写的代码也不会为每个图层启动正确的动画。

请注意,通过将removedOnCompletion设置为YES,您的动画将运行,然后对象将跳回到最后的起始点。你可能希望那是NO。

+0

感谢您回答布拉德。虽然动画的开始/结束位置不是我的问题,但您做了很好的观察。在我的情况下,我已经删除了OnCompletion = YES冗余(这是默认值)。我的步骤是:1)将图层位置设置为最终位置; 2)分别计算动画的开始/结束位置(动画结束位置是当前图层位置)。我还将'fillMode'保留为默认值(kCAFillModeRemoved)。我的问题不是动画期间/之后的图层的位置,它与顺序动画有关。 – 2010-12-09 17:06:57