Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rotate UIImageView clockwise

This should be simple, but I'm having trouble rotating a UIImageView a full 360 degrees, repeated forever.

[UIView animateWithDuration:0.5 delay:0 options:UIViewAnimationOptionAllowUserInteraction | UIViewAnimationOptionRepeat | UIViewAnimationOptionCurveLinear | UIViewAnimationOptionBeginFromCurrentState animations:^{
    self.reloadButton.imageView.transform = CGAffineTransformRotate(self.reloadButton.imageView.transform, -M_PI);
} completion:^(BOOL finished) {

}];

According to the docs, the signedness of the angle I pass to CGAffineTransformRotate determines the direction of the rotation, but the above code rotates counterclockwise. Same with M_PI.

The angle, in radians, by which this matrix rotates the coordinate system axes. In iOS, a positive value specifies counterclockwise rotation and a negative value specifies clockwise rotation. In Mac OS X, a positive value specifies clockwise rotation and a negative value specifies counterclockwise rotation.

like image 565
Morrowless Avatar asked May 08 '12 06:05

Morrowless


1 Answers

Christoph is already going the correct way, but there is a far better way to keep it spinning without reinvoke it in the animation delegates every time it ends. This is simply wrong.

Just set the repeatCount property of your animation to HUGE_VALF.

CABasicAnimation* animation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
animation.fromValue = @0.0f;
animation.toValue = @(2*M_PI);
animation.duration = 0.5f;             // this might be too fast
animation.repeatCount = HUGE_VALF;     // HUGE_VALF is defined in math.h so import it
[self.reloadButton.imageView.layer addAnimation:animation forKey:@"rotation"];

As stated in the documentation, this will cause the animation to repeat forever.

like image 188
yinkou Avatar answered Sep 18 '22 08:09

yinkou