BoredToDeath BoredToDeath - 1 year ago 97
iOS Question

how to spin a image continously

i have an wheel image in .png format,i want to know how can i animate so that it rotates continously,i searched on stackoverflow and found certain snippets of code which helped me rotate my image but it wouldnt rotate continously,it would just rotate for a few seconds and stop,the code as follows

the code in viewdidload

UIImageView *imageToMove =
[[UIImageView alloc] initWithImage:[UIImageimageNamed:@"horo_circle.png"]];
[self.view addSubview:imageToMove];

[self rotateImage:imageToMove duration:5.0
curve:UIViewAnimationCurveEaseIn degrees:180];

and the animation

- (void)rotateImage:(UIImageView *)image duration:(NSTimeInterval)duration
curve:(int)curve degrees:(CGFloat)degrees
// Setup the animation
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:duration];
[UIView setAnimationCurve:curve];
[UIView setAnimationBeginsFromCurrentState:YES];

// The transform matrix
CGAffineTransform transform =
image.transform = transform;

// Commit the changes
[UIView commitAnimations];

and the following lines after the import

#define M_PI 3.14159265358979323846264338327950288 /* pi */

#define DEGREES_TO_RADIANS(angle) (angle / 180.0 * M_PI)

Answer Source

You are better of doing this with a CABasicAnimation:

if ([self.spinnerOverlay animationForKey:@"SpinAnimation"] == nil) {
    CABasicAnimation* animation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    animation.fromValue = [NSNumber numberWithFloat:0.0f];
    animation.toValue = [NSNumber numberWithFloat: 2*M_PI];
    animation.duration = 10.0f;
    animation.repeatCount = INFINITY;
    [self.spinnerOverlay.layer addAnimation:animation forKey:@"SpinAnimation"];

In this code I check whether the animation is all ready set, not need to set it again. The spinnerOverlay is in your case the UIImageView you want to rotate.

To stop the animation:

  [self.spinnerOverlay.layer removeAnimationForKey:@"SpinAnimation"];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download