怎么做自动旋转CALayer

时间:2010-10-11 21:26:13

标签: iphone

当我点击视图时,它会创建一个星形路径。

现在我要旋转添加到CALayer的星星。

任何人都可以帮助我....如何在iphone上旋转CALayer。

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
        UITouch *touch=[touches anyObject];
        currentPoint=[touch locationInView:self.view];
        CGMutablePathRef starPath;
        rootLayer   = [CALayer layer];
        rootLayer.frame = self.view.bounds;
        [self.view.layer addSublayer:rootLayer];
        starPath = CGPathCreateMutable();
        CGPathMoveToPoint(starPath, NULL,currentPoint.x,currentPoint.y+15.0f);
        for(int i = 1; i < 5; ++i)
        {
        CGFloat  x =15.0*sinf(i * 4.0 * M_PI/5.0);
        CGFloat y =15.0*cosf(i * 4.0 * M_PI/5.0);
        CGPathAddLineToPoint(starPath, NULL,currentPoint.x+x,currentPoint.y+y);
        }
        CGPathCloseSubpath(starPath);
        shapeLayer=[CAShapeLayer layer];
        shapeLayer.path = starPath;
        fillColor = [UIColor colorWithHue:0.825 saturation:1 brightness:1 alpha:1.0];
        shapeLayer.fillColor = fillColor.CGColor;
        [rootLayer addSublayer:shapeLayer];
        CGPathRelease(starPath);
        float zDistance=30;
        CATransform3D aTransform=CATransform3DIdentity;
        aTransform.m34=1.0/-zDistance;
        rootLayer.sublayerTransform=aTransform;
        [self addAnimationToLayer:rootLayer];
    }

    -(void)addAnimationToLayer:(CALayer *)layer
    {
    CABasicAnimation *theAnimation;
    theAnimation=[CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    theAnimation.fromValue=[NSNumber numberWithDouble:M_PI_2];
    //theAnimation.toValue=[NSNumber numberWithFloat:6.0f*M_PI/180.0f];
    theAnimation.duration=100;
    //  theAnimation.autoreverses=TRUE;
    theAnimation.speed=100;
    theAnimation.repeatCount=10;
    [layer addAnimation:theAnimation forKey:@"transform"] ;
    }

1 个答案:

答案 0 :(得分:1)

像这样使用CAKeyframeAnimation:

CAKeyframeAnimation *spinAnim = [CAKeyframeAnimation animationWithKeyPath:@"transform"];
spinAnim.duration = 3.0; // some appropriate duration

float firstHalfRotation = M_PI;
float secondHalfRotation = (M_PI * 2.0);

spinAnim.values = [NSArray arrayWithObjects:
                   [NSValue valueWithCATransform3D:CATransform3DMakeRotation(0, 0, 0, 1)], 
                   [NSValue valueWithCATransform3D:CATransform3DMakeRotation(firstHalfRotation, 0, 0, 1)], 
                   [NSValue valueWithCATransform3D:CATransform3DMakeRotation(secondHalfRotation, 0, 0, 1)], 
                   nil];
[layer addAnimation:spinAnim forKey:@"spin"];
相关问题