Search code examples
ioscalayeruiviewanimationcgaffinetransform

CALayer rotate by direction


I'm trying to rotate a CALayer, first of all I rotate it by -30 degrees, so it turns left.

[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.5];
self.transform = CGAffineTransformMakeRotation(DEGREES_TO_RADIANS(-30));
[UIView commitAnimations];

Now I want it to complete the rotate, do another rotation starting left, but it takes the shortest path.

[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.5];
self.transform = CGAffineTransformMakeRotation(DEGREES_TO_RADIANS(-30));
[UIView commitAnimations];

How can I force it's rotation direction ?


Solution

  • You can use a CABasicAnimation to rotate to a specific angle.

    CABasicAnimation *rotate = 
        [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
    rotate.toValue = @(M_PI*2); 
    rotate.duration = 1.0; // your duration
    
    [yourView.layer addAnimation:rotate 
                          forKey:@"myRotationAnimation"];
    

    There are some more parameters that you can use to configure how the animation looks (for example timing function).

    By default the animation will remove itself after it completes so you should update to the end value (this has been explained over and over in all the "how do I rotate ..."-questions.

    Also, you need QuartzCore.framework for Core Animation (CALayer and CABasicAnimation in this example)