2011-03-28 142 views
12

我正在研究益智游戏,我需要将拼图块旋转到每个双击的90度角。旋转UIView iPhone

我试图做两种不同的方式。第一种方法是这样的一种:

[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到以前的状态。

如何在不存在这些问题的情况下使用动画旋转拼图块?

回答

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) 
+0

伟大而简单的解决方案。 – CroiOS 2012-11-22 15:58:28

+0

它实际上并不是我的动画,它只是在两种旋转状态之间切换...... – 2014-06-26 17:18:19

5

你的第一个方法是好的,exept的角度是弧度

[UIView beginAnimations:@"rotate" context:nil]; 
[UIView setAnimationDuration:0.5]; 
self.transform = CGAffineTransformMakeRotation(90/180*M_PI); 
[UIView commitAnimations]; 
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]; 
+0

只是为了澄清,定义比c函数更快。因为MAX,MIN,ABS也是定义。 – 2014-03-21 15:07:07

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]; 
     } 
    }]; 
}