2010-07-01 57 views
0

我有一张图片放在CALayer中,然后将该图层添加为主视图的子图层。当我尝试围绕它的Z轴制作动画时,我所看到的只是一幅静态图像。为什么我的图层不能围绕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; 
} 

回答

1

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

你会想要在transform.rotation.z keypath中执行动画,如this answer中所述。这是Core Animation提供的助手键路径,并且由于您的起始值和结束值(旋转的角度)不同,Core Animation不会执行与转换相同的优化。

+0

Thanx Brad。我已经解决了这个问题。 – Rahul 2010-07-01 23:00:52

+0

如果布拉德解决了您的问题,那么应该将他的答案标记为已接受的答案。 ;-) – 2010-07-05 22:08:32

0

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

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

将图层上的变换设置为该图层,然后像您一样创建动画。