像轮子动画一样旋转图像,并在随机位置停止

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了像轮子动画一样旋转图像,并在随机位置停止相关的知识,希望对你有一定的参考价值。

我正在创建一个游戏,其中骰子动作以圆圈显示。当用户点击滚轮时,它会旋转并停在随机位置。我搜索并找到了一些我试图实现的代码: -

 [UIView beginAnimations:@"RotationAnimation" context:nil];
 CALayer *myLayer = diceCircle.layer;
    CABasicAnimation *fullRotationAnimation;
    fullRotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
    fullRotationAnimation .fromValue = [NSNumber numberWithFloat:0];
   // fullRotationAnimation.toValue = [NSNumber numberWithFloat:((360*M_PI)/180)];
    fullRotationAnimation.toValue = [NSNumber numberWithFloat:angle];

    fullRotationAnimation.duration = 0.5;          // speed for the rotation. Smaller number is faster
    fullRotationAnimation.repeatCount = 1;  // number of times to spin. 1 = once
    [myLayer addAnimation:fullRotationAnimation forKey:@"360"];

    [UIView commitAnimations];

角度来自: -

-(IBAction)diceButtonClicked:(id)sender
{
    float angle=arc4random()%360;
    NSLog(@"%f",angle);
    float rad=radians(angle);
    NSLog(@"%f",rad);
    [self rotateDiceMethod:rad];
}

但是车轮每次都停在同一个位置,也不总是动画。请给我一些实现所需功能的方法或示例代码。

提前致谢!

答案

这是我执行相同任务的旧代码:

CGFloat randValue= arc4random() % 10;
self.angleRotate =  (randValue+30);
CABasicAnimation *spinAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
spinAnimation.fromValue = [NSNumber numberWithFloat:self.angle];
spinAnimation.toValue = [NSNumber numberWithFloat:self.angle+self.angleRotate];
spinAnimation.duration = 2.0f;
spinAnimation.cumulative = YES;
spinAnimation.additive = YES;
spinAnimation.removedOnCompletion = NO;
spinAnimation.delegate = self;
spinAnimation.timingFunction = [CAMediaTimingFunction
             functionWithName:kCAMediaTimingFunctionEaseOut];
spinAnimation.fillMode = kCAFillModeForwards;
[self.arrow.layer addAnimation:spinAnimation forKey:@"spinAnimation"];

并且当旋转停止时

- (void)animationDidStop:(CAAnimation *)spinAnimation finished:(BOOL)flag{
    self.angle += self.angleRotate;
    while (self.angle >= M_PI*2.0) {
        self.angle -=  M_PI*2.0;
    }
    NSLog(@"angleRotate value is: %f", self.angleRotate);
    NSLog(@"angle value is: %f", self.angle);
    self.angleRotate = 0;
}

以上是关于像轮子动画一样旋转图像,并在随机位置停止的主要内容,如果未能解决你的问题,请参考以下文章

CAGradientLayer 的中心在旋转动画上返回错误的位置

如何在Android中旋转位图,使图像中心平滑,无振荡运动

停止动画不适用于图像视图

如何在 Swift 中的位置上设置加扰字母的动画?

按下“停止”按钮时如何停止动画并冻结图像

在 UIScrollView 问题中旋转 UIImageView