我有一个.png格式的轮子图像,我想知道我怎么能动画,以便它连续旋转,我搜索stackoverflow并找到某些代码片段,帮助我旋转我的图像,但它不会连续旋转,它会只需旋转几秒钟即可停止,代码如下
viewdidload中的代码
- UIImageView *imageToMove =
- [[UIImageView alloc] initWithImage:[UIImageimageNamed:@"horo_circle.png"]];
- [self.view addSubview:imageToMove];
- [self rotateImage:imageToMove duration:5.0
- curve:UIViewAnimationCurveEaseIn degrees:180];
和动画
- - (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];
- }
以及导入后的以下行
- #define M_PI 3.14159265358979323846264338327950288 /* pi */
- #define DEGREES_TO_RADIANS(angle) (angle / 180.0 * M_PI)
解决方法
您最好使用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"];
- }
在这段代码中,我检查动画是否全部准备就绪,不需要再次设置.
在您的情况下,spinnerOverlay是您要旋转的UIImageView.
要停止动画:
- [self.spinnerOverlay.layer removeAnimationForKey:@"SpinAnimation"];