为什么我的图层不会围绕Z轴动画?

时间:2010-07-01 20:22:43

标签: iphone cocoa-touch core-animation

我有一张放在CALayer中的图像,然后将该图层添加为主视图的子图层。当我尝试围绕Z轴设置动画时,我看到的只是静态图像。

为什么我的图层不会动画?相关代码如下:

- (void)viewDidLoad {

    UIImage *myImage = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"about" ofType:@"png"]];
    earthLayer = [CALayer layer];
    [earthLayer setContents:(id)[myImage CGImage]];
    [earthLayer setBounds:CGRectMake(240,360, 40, 200)];
    [earthLayer setPosition:CGPointMake(280, 280)];
    [earthLayer setName:@"earth"];



    [earthLayer addAnimation:[self animationForSpinning] forKey:@"Rahul"];//here animatin is being added to the layer.. 

    [[self.view layer] addSublayer:earthLayer];

    //[self spinLayer:earthLayer];


}

//the animation method which returns a CAAnimation.

- (CAAnimation*)animationForSpinning {

    // Create a transform to rotate in the z-axis
    float radians = DegreeToRadian( 360 );
    CATransform3D transform;
    transform = CATransform3DMakeRotation(radians, 0, 1.0,0, 1.0);

    // Create a basic animation to animate the layer's transform
    CABasicAnimation* animation;
    animation = [CABasicAnimation animationWithKeyPath:@"transform"];

    // Now assign the transform as the animation's value. While
    // animating, CABasicAnimation will vary the transform
    // attribute of its target, which for this transform will spin
    // the target like a wheel on its z-axis. 
    animation.toValue = [NSValue valueWithCATransform3D:transform];

    animation.duration = 2;  // two seconds
    animation.cumulative = YES;
    animation.repeatCount = 10000;//  "forever"
    return animation;
}

2 个答案:

答案 0 :(得分:1)

您的问题似乎是您尝试使用360度变换为图层设置动画。对于核心动画,由360度转换的图层与起始图层完全相同,因此不会执行动画。

this answer中所述,您希望围绕transform.rotation.z密钥路径制作动画。这是Core Animation提供的辅助键路径,并且由于您的起始值和结束值(旋转的角度)不同,因此Core Animation不会使用变换进行相同的优化。

答案 1 :(得分:0)

你需要在动画之前对你的图层应用透视变换,否则你所做的旋转看起来不正确。

CATransform3D transform = CATransform3DIdentity; transform.m34 = 1.0 / -2000;

将图层上的变换设置为,然后像你一样动画。