Joseph800
Joseph800

Reputation: 61

How do you rotate UIView, UIImageView or CALayer animated 360˚?

How do you rotate UIView, UIImageView or CALayer animated 360 degress without using OpenGL ES?

Upvotes: 5

Views: 6902

Answers (2)

hfossli
hfossli

Reputation: 22962

#import <QuartzCore/QuartzCore.h>

CABasicAnimation *fullRotation;
fullRotation = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
fullRotation.fromValue = @(0.0);
fullRotation.toValue = @((360.0 * M_PI)/180.0);
fullRotation.duration = 3.5f;
fullRotation.repeatCount = MAXFLOAT;

[view.layer addAnimation:fullRotation forKey:@"rotation-animation"];   

If you want to change the anchor point it to rotates around then you can do

CGRect frame = view.layer.frame;
self.anchorPoint = CGPointMake(0.5, 0.5); // rotates around center
self.frame = frame;

Upvotes: 28

randallmeadows
randallmeadows

Reputation: 863

Presumably you mean animate rotating a UIImage around a full 360°? In my experience, the way to accomplish a full circle rotation is to chain multiple animations together:

- (IBAction)rotate:(id)sender
{
   [UIView beginAnimations:@"step1" context:NULL]; {
      [UIView setAnimationDuration:1.0];
      [UIView setAnimationDidStopSelector:@selector(animationDidStop:finished:context:)];
      [UIView setAnimationDelegate:self];
     [imageView.transform = CGAffineTransformMakeRotation(120 * M_PI / 180);
   } [UIView commitAnimations];
}

- (void)animationDidStop:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context
{
   if ([animationID isEqualToString:@"step1"]) {
      [UIView beginAnimations:@"step2" context:NULL]; {
         [UIView setAnimationDuration:1.0];
         [UIView setAnimationDidStopSelector:@selector(animationDidStop:finished:context:)];
         [UIView setAnimationDelegate:self];
         imageView.transform = CGAffineTransformMakeRotation(240 * M_PI / 180);
      } [UIView commitAnimations];
   }
   else if ([animationID isEqualToString:@"step2"]) {
      [UIView beginAnimations:@"step3" context:NULL]; {
         [UIView setAnimationDuration:1.0];
         [UIView setAnimationDidStopSelector:@selector(animationDidStop:finished:context:)];
         [UIView setAnimationDelegate:self];
         imageView.transform = CGAffineTransformMakeRotation(0);
      } [UIView commitAnimations];
   }
}

I've left the easeIn/easeOut curve (instead of linear) in place, so you can see the individual animations.

Upvotes: 2

Related Questions