多个CAKeyframeAnimation同时在不同的层中

Edu*_*lho 5 iphone core-animation ipad

现在有人如何使用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);
}
Run Code Online (Sandbox Code Playgroud)

现在,假设我在我的棋盘游戏中添加了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];
Run Code Online (Sandbox Code Playgroud)

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

有任何想法吗?

提前致谢.

Bra*_*son 4

如果您想将一系列像这样的动画分组,以便保证它们同步,您可以将它们包装在 CATransaction 中:

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

// Do animations

[CATransaction commit];     
Run Code Online (Sandbox Code Playgroud)

但是,我不太确定为什么您编写的代码没有为每一层触发正确的动画,即使它们没有同步。

请注意,通过设置removedOnCompletion为 YES,您的动画将运行,然后对象将在结束时跳回其起点。你可能希望它是“否”。