2011-03-28 158 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]; 
     } 
    }]; 
}