8

Can anyone tell me how to rotate an image in circular motion

Bhargav Rao
  • 45,811
  • 27
  • 120
  • 136
abhinav
  • 99
  • 1
  • 1
  • 3

5 Answers5

28

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"];
}
mahboudz
  • 39,028
  • 16
  • 96
  • 123
3

based on mahboudz's answer, you can set it to infinitely spin by setting:
rotationAnimation.repeatCount = HUGE_VALF;

kentb
  • 31
  • 2
2

If you mean, "How do you make an image follow a circular path?", then the pseudocode would be:

image.x = circleCentre.x + cos(angle) * circleRadius;
image.y = circleCentre.y + sin(angle) * circleRadius;
angle += 5;
Sam
  • 3,551
  • 3
  • 31
  • 48
1

This question asks the same thing, although in different words. The answers in that question, as well as in this question should provide a way to animate a UIView (UIImageView is simply a subclass of this) about its center for 360 degrees or more.

Community
  • 1
  • 1
Brad Larson
  • 169,393
  • 45
  • 393
  • 567
1

Creating the animation

- (CABasicAnimation *)spinAnimationWithDuration:(CGFloat)duration clockwise:(BOOL)clockwise repeat:(BOOL)repeats
{
    CABasicAnimation *anim = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    anim.toValue = clockwise ? @(M_PI * 2.0) : @(M_PI * -2.0);
    anim.duration = duration;
    anim.cumulative = YES;
    anim.repeatCount = repeats ? CGFLOAT_MAX : 0;
    return anim;
}

Add it to a view

CABasicAnimation *animation = [self spinAnimationWithDuration:1.0 clockwise:YES repeat:YES];
[self.spinningView.layer addAnimation:animation forKey:@"rotationAnimation"];

How is this answer different from @mahboudz's answer? You will have way cleaner code if most of your functions returns objects instead of just manipulating some objects here and there.

hfossli
  • 22,108
  • 10
  • 113
  • 129