旋转 UIView iPhone

12

我正在制作一个拼图游戏,需要在每个双击时将拼图块旋转90度。

我尝试了两种不同的方法,第一种方法是这样的:

[UIView beginAnimations:@"rotate" context:nil];
[UIView setAnimationDuration:0.5];
self.transform = CGAffineTransformMakeRotation(90);
[UIView commitAnimations];

唯一的问题是这个部分没有旋转 90 度; 而是旋转了约 100 度,并且此动画正在修改拼图块的帧 UIView

这是我的控制台输出:

frame BEFORE ROTATION: {{35, 178}, {80, 80}}

frame AFTER ROTATION: {{21.3172, 164.317}, {107.366, 107.366}}
我尝试的第二种方法是这样的:
CABasicAnimation* spinAnimation = [CABasicAnimation
                                       animationWithKeyPath:@"transform.rotation"];
spinAnimation.toValue = [NSNumber numberWithFloat:1];
[self.layer addAnimation:spinAnimation forKey:@"spinAnimation"];
问题在于使用这种方法后,旋转结束后将会翻转我的 UIView 到先前的状态。
如何在进行动画旋转时避免这些问题呢?
4个回答

48

尝试

[UIView beginAnimations:@"rotate" context:nil];
[UIView setAnimationDuration:0.5];
self.transform = CGAffineTransformMakeRotation(DegreesToRadians(90));
[UIView commitAnimations];

你可以将DegreesToRadians定义为

#define DegreesToRadians(x) ((x) * M_PI / 180.0)

对我来说它实际上并没有动画效果,只是在两个旋转状态之间切换... - Eliza Wilson

5

您的第一种方法不错,只是角度以弧度为单位

[UIView beginAnimations:@"rotate" context:nil];
[UIView setAnimationDuration:0.5];
self.transform = CGAffineTransformMakeRotation(90/180*M_PI);
[UIView commitAnimations];

4

现在大多数人都使用iOS动画块进行动画制作。所以我建议使用类似这样的代码(当然你可以设置自己的时间、动画选项和旋转角度)。享受吧!

[UIView animateWithDuration:0.4f delay:0.0f options:UIViewAnimationOptionCurveEaseOut animations:^{
        YOURVIEW.transform = CGAffineTransformMakeRotation(DegreesToRadians(180));
    } completion:^(BOOL finished) {

    }];

#define DegreesToRadians(x) ((x) * M_PI / 180.0)

如果您正在寻找360度的旋转,但因为不希望动画旋转到最终恰好回到起点的位置,所以需要使用类似以下代码:

- (void)rotateSpinningView:(UIView *)viewToSpin{
    [UIView animateWithDuration:1.5 delay:0 options:UIViewAnimationOptionCurveLinear animations:^{
        [viewToSpin setTransform:CGAffineTransformRotate(viewToSpin.transform, M_PI_2)];
    } completion:^(BOOL finished) {
        if (finished && !CGAffineTransformEqualToTransform(viewToSpin.transform, CGAffineTransformIdentity)) {
            [self rotateSpinningView:viewToSpin];
        }
    }];
}

2

我认为最好的方法是声明C函数

static inline CGFloat degreesToRadians(CGFloat degrees) {return (degrees) * M_PI / 180.0f;}

然后像这样使用它

[UIView beginAnimations:@"rotate" context:nil];
[UIView setAnimationDuration:0.5];
self.transform = CGAffineTransformMakeRotation(degreesToRadians(180.0f));
[UIView commitAnimations];

只是为了澄清,定义比 C 函数更快。因此 MAX、MIN、ABS 也是定义。 - Ratata Tata

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接