这应该很简单,但是我无法将UIImageView
旋转360度,永远重复。
[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) {
}];
根据文档,我传递给CGAffineTransformRotate
的角度的符号确定旋转方向,但上面的代码逆时针旋转。与M_PI
相同。
以弧度表示此矩阵旋转坐标的角度 系统轴。在iOS中,正值指定逆时针 旋转和负值指定顺时针旋转。在Mac OS中 X,正值指定顺时针旋转和负值 指定逆时针旋转。
答案 0 :(得分:14)
Christoph已经采用了正确的方式,但是有一种更好的方法可以让它保持旋转状态,而不必在动画代表每次结束时重新调用它。这是完全错误的。
只需将动画的repeatCount属性设置为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"];
如上所述in the documentation,这将导致动画永远重复。
答案 1 :(得分:1)
抱歉错过了第一部分,视图使用较小的角度旋转正常:
[UIView animateWithDuration:0.5 delay:0 options:UIViewAnimationOptionAllowUserInteraction | UIViewAnimationOptionRepeat | UIViewAnimationOptionCurveLinear | UIViewAnimationOptionBeginFromCurrentState animations:^{
redView.transform = CGAffineTransformRotate(redView.transform, M_PI_2);
} completion:^(BOOL finished) {
}];
我找不到任何有意义的解释,为什么它失败了M_PI。
答案 2 :(得分:1)
前一段时间我遇到过同样的问题。 我不记得这个问题的原因,但这是我的解决方案:
/**
* Incrementally rotated the arrow view by a given angle.
*
* @param degrees Angle in degrees.
* @param duration Duration of the rotation animation.
*/
- (void)rotateArrowViewByAngle:(CGFloat)degrees
withDuration:(NSTimeInterval)duration {
CABasicAnimation *spinAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
spinAnimation.fromValue = [NSNumber numberWithFloat:self.currentAngle / 180.0 * M_PI];
spinAnimation.toValue = [NSNumber numberWithFloat:degrees / 180.0 * M_PI];
spinAnimation.duration = duration;
spinAnimation.cumulative = YES;
spinAnimation.additive = YES;
spinAnimation.removedOnCompletion = NO;
spinAnimation.delegate = self;
spinAnimation.fillMode = kCAFillModeForwards;
[self.arrowView.layer addAnimation:spinAnimation forKey:@"spinAnimation"];
self.currentAngle = degrees;
}
然后你可以使用委托方法
- (void)animationDidStart:(CAAnimation *)theAnimation
- (void)animationDidStop:(CAAnimation *)theAnimation finished:(BOOL)flag
旋转保持旋转。 此外,学位和持续时间参数可能非常高......如果这足够了。
更新:
正如yinkou所说,
spinAnimation.repeatCount = HUGE_VALF; // HUGE_VALF is defined in math.h so import it
在委托中重新启动动画会更好。
请注意:
self.currentAngle是记住当前最终轮换的属性。
我需要它让视图左右旋转。
答案 3 :(得分:1)
我为此编写了UIImageView类:https://gist.github.com/alexhajdu/5658543。
只需使用:
[_myImageView rotate360WithDuration:1.0 repeatCount:0]; //0 for infinite loop