I'm trying to rotate a UIImageView
360 degrees, and have looked at several tutorials online. I could get none of them working, without the UIView
either stopping, or jumping to a new position.
- How can I achieve this?
The latest thing I've tried is:
[UIView animateWithDuration:1.0
delay:0.0
options:0
animations:^{
imageToMove.transform = CGAffineTransformMakeRotation(M_PI);
}
completion:^(BOOL finished){
NSLog(@"Done!");
}];
But if I use 2*pi, it doesn't move at all (since it's the same position). If I try to do just pi (180 degrees), it works, but if I call the method again, it rotates backwards.
EDIT:
[UIView animateWithDuration:1.0
delay:0.0
options:0
animations:^{
[UIView setAnimationRepeatCount:HUGE_VALF];
[UIView setAnimationBeginsFromCurrentState:YES];
imageToMove.transform = CGAffineTransformMakeRotation(M_PI);
}
completion:^(BOOL finished){
NSLog(@"Done!");
}];
doesn't work either. It goes to 180
degrees, pauses for a split second, then resets back to 0
degrees before it starts again.
Swift 3 :
I think you should better add a
UIVIew
Category:Implementation UIView (Rotate)
Not using this methods :)
If all you want to do is rotate the image endlessly, this works quite well, and is very simple:
In my experience, this works flawlessly, but be sure your image is capable of being rotated around its center without any offsets, or the image animation will "jump" once it makes it around to PI.
To change the direction of the spin, change the sign of
angle
(angle *= -1
).Update Comments by @AlexPretzlav made me revisit this, and I realized that when I wrote this the image I was rotating was mirrored along both the vertical and horizontal axis, meaning the image was indeed only rotating 90 degrees and then resetting, though it looked like it was continuing to rotate all the way around.
So, if your image is like mine was, this will work great, however, if the image is not symmetrical, you'll notice the "snap" back to the original orientation after 90 degrees.
To rotate a non-symmetrical image, you're better off with the accepted answer.
One of these less elegant solutions, seen below, will truly rotate the image, but there may be a noticeable stutter when the animation is restarted:
You could also do this just with blocks, as @richard-j-ross-iii suggests, but you will get a retain loop warning since the block is capturing itself:
David Rysanek's awesome answer updated to Swift 4:
Swift :
Found a method (I modified it a bit) that worked perfectly for me: iphone UIImageView rotation