Can I use CGAffineTransformMakeRotation to rotate a view more than 360 degrees?

bwinton picture bwinton · Feb 12, 2009 · Viewed 25.2k times · Source

I'm writing an iPhone app, and I've got an image which I'ld like to have swirl outwards.

Currently my code looks like this (wrapped in a beginAnimations/commitAnimations block):

scale = CGAffineTransformScale(CGAffineTransformIdentity, 5.0f, 5.0f);
swirl = CGAffineTransformRotate(scale, M_PI);
[player setTransform:swirl];    
[player setAlpha:0.0f];

But I find that if I try to change the angle of the rotation to, say, 4*M_PI, it doesn't rotate at all. Is it possible to get a 720˚ rotation using CGAffineTransformRotate, or do I have to switch to another technology?

If I have to switch to another technology, would you recommend using another thread (or a timer) to do the animation myself, or would OpenGL be a better route to go?

Thanks,
Blake.

Answer

mahboudz picture mahboudz · Sep 14, 2009

You can rotate a view, by some number of radians, regardless of whether it is less than a full rotation or many multiples of a full rotation, without having to split the rotation into pieces. As an example, the following code will spin a view, once per second, for a specified number of seconds. You can easily modify it to spin a view by a certain number of rotations, or by some number of radians.

- (void) runSpinAnimationWithDuration:(CGFloat) duration;
{
    CABasicAnimation* rotationAnimation;
    rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    rotationAnimation.toValue = [NSNumber numberWithFloat: M_PI * 2.0 /* full rotation*/ * rotations * duration ];
    rotationAnimation.duration = duration;
    rotationAnimation.cumulative = YES;
    rotationAnimation.repeatCount = 1.0; 
    rotationAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];

    [myView.layer addAnimation:rotationAnimation forKey:@"rotationAnimation"];
}