how to spin an image continuously
Asked Answered
S

5

6

I have an wheel image in .png format, I want to know how can i animate so that it rotates continuously, I searched on stackoverflow and found certain snippets of code which helped me rotate my image but it wouldn't rotate continuously, 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 = 
    CGAffineTransformMakeRotation(DEGREES_TO_RADIANS(degrees));
    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)
Screak answered 8/11, 2012 at 14:46 Comment(2)
There are other questions that ask exactly this (continuous spin) My answer to the same question hereReece
possible duplicate of UIView Infinite 360 degree rotation animation?Reece
S
50

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"];
Sidsida answered 8/11, 2012 at 14:54 Comment(1)
If you need to put it in viewDidLoad, wrap it in a dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(NSEC_PER_MSEC * 1000)), dispatch_get_main_queue(), ^{ ... } blockRiff
E
3

The code bellow will spin a UIImageView called iconView continiously until rotate == NO.

The image will always return to its original position.

- (void)performRotationAnimated
{
    [UIView animateWithDuration:0.5
                          delay:0
                        options:UIViewAnimationOptionCurveLinear
                     animations:^{

                         self.iconView.transform = CGAffineTransformMakeRotation(M_PI);
                     }
                     completion:^(BOOL finished){

                         [UIView animateWithDuration:0.5
                                               delay:0
                                             options:UIViewAnimationOptionCurveLinear
                                          animations:^{

                                              self.iconView.transform = CGAffineTransformMakeRotation(0);
                                          }
                                          completion:^(BOOL finished){

                                              if (_rotate) {

                                                  [self performRotationAnimated];
                                              }
                                          }];
                     }];
}

This is a variation on the same theme.

(Total duration: 2 * 0.5 = 1 sec for a spin)

Works like magic!

Ectomy answered 27/5, 2015 at 23:37 Comment(2)
What is _rotate?Curitiba
It's a global boolean value. If TRUE then it continues to spin if FALSE it stops in its original position. I should have used if (self.keepRotating) {}Ectomy
T
2

Here is another way to do it with a timer. In your viewController.h file, you'll need to declare your timer and image:

@interface ViewController : UIViewController

{

    IBOutlet UIImageView *spinningImage;

    NSTimer *spinTimer;

}

Next, in your ViewController.m, you add this code and can make the spin go faster by lowering the time interval or by increasing the transform interval.

-(void) viewDidLoad {
    spinTimer = [NSTimer scheduledTimerWithTimeInterval:.01 target: self selector:@selector(spinVoid) userInfo:nil repeats:YES];
}

-(void) spinVoid {

    spinningImage.transform = CGAffineTransformRotate(spinningImage.transform, 0.001);

}

Hope this helps!

Torbart answered 3/5, 2016 at 22:51 Comment(0)
D
1

Now that we're at iOS6, please consider switching to block based animations (that are available since iOS 4.0) rather than the classical method. Try this:

[UIView animateWithDuration:duration delay:0.0 options:UIViewAnimationOptionRepeat animations:^{

image.transform = CGAffineTransformMakeRotation(DEGREES_TO_RADIANS(degrees));

    } completion:nil];
Deloresdeloria answered 8/11, 2012 at 14:53 Comment(1)
i tried the above method and used your method but i encountered the same problem i.e it rotates and then starts again from the same placeScreak
B
-1

Using the method you've chosen for animations :

 [UIView setAnimationRepeatCount:10000000];

or, you can specify the UIViewAnimationOptionRepeat flag in the blocks method animateWithDuration:delay:options:animations:completion:

Battledore answered 8/11, 2012 at 14:54 Comment(6)
well yea - you're only rotating 180 degrees, what did you expect? If you want it to rotate all 360 before repeating, just replace 180 with 360.Battledore
@deanWombourne..yeah that thing was intuitive and i tried using 360,but if i do that it doesnt rotate at all..Screak
Oh, that's annoying. I suspect that when your transform is given a rotation of 360 it's wrapping round back to 0. You might have to go to a more complicated api to achieve this - have you tried @Sidsida answer?Battledore
well yeah..i dont know why but i keep getting this linker error regarding the quartzcoreframework..i hadnt added quartzcoreframework but even after adding i am facing some linker error issuesScreak
i get two errors and one warning..they are as follows ld: warning: ignoring file /Users/apple/Desktop/justforcells/QuartzCore.framework/QuartzCore, file was built for unsupported file format which is not the architecture being linked (i386) Undefined symbols for architecture i386: "_OBJC_CLASS_$_CALayer", referenced from: objc-class-ref in ViewController.o "_OBJC_CLASS_$_CABasicAnimation", referenced from: objc-class-ref in ViewController.o ld: symbol(s) not found for architecture i386Screak
That's odd - why is the linker looking for files on your Desktop? How are you adding frameworks to your project?Battledore

© 2022 - 2024 — McMap. All rights reserved.