2017-02-20 32 views
0

我有一個應用程序,我需要重現骰子動畫。每次擲骰子時,我都應該改變他在X軸上的位置和他的旋轉。同時旋轉和改變視圖位置?

骰子是一個UIButtonUIView與16個像素更大!當用戶滾動時,我創建了一個用於旋轉的動畫,同時我爲X視圖值的變化設置了動畫。當動畫完成時,我嘗試修復一個隨機停止位置。

看看我的代碼,以更好地理解。

這是我的旋轉動畫:

CABasicAnimation* animation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"]; 
animation.fromValue = [NSNumber numberWithFloat:0.0f]; 
animation.toValue = [NSNumber numberWithFloat: 2*M_PI]; 
animation.duration = 0.2; 
animation.repeatCount = 2; 
[dice.layer addAnimation:animation forKey:@"SpinAnimation"]; 

int min = -20; 
int maxim = 20; 
int rndValue = min + arc4random() % (maxim - min); 

// Here I change x value; 
CGRect rct = dice.superview.frame; 
rct.origin.x = n + rndValue; 
rct.size.width = dice.superview.bounds.size.width; 
rct.size.height = dice.superview.bounds.size.height; 
[UIView animateWithDuration:0.4 animations:^{ 
    dice.superview.frame = rct; 
}completion:^(BOOL finished){ 
    //Here, after the animation is done, i want to put a random rotation value. 
    float degrees = arc4random() % 30; 
    dice.superview.layer.anchorPoint = CGPointMake(0.5, 0.5); 
    dice.superview.transform = CGAffineTransformMakeRotation(degrees * M_PI/180); 
}]; 

我的問題是不是每次(預計第一個,當我搖)骰子(意見太)變小,因爲視圖框的大小正在改變,我可以沒有發現問題或任何其他解決方案。 PS:如果我只使用其中的一種(旋轉或改變X軸值),骰子保持相同的大小。

我已經在網上搜索了很多,但對我沒有任何用處。任何人有一個想法,請?非常感謝!

回答

0

我終於找到了我的問題的答案,我在這裏發佈我的解決方案,也許其他人會遇到同樣的問題。

問題由骰子移動而成。 當我移動骰子時,我改變了它的框架,那是我的錯誤。如果你將改變骰子

替換爲幀動畫改變的中心點它解決了這個問題:

[UIView animateWithDuration:0.4 animations:^{ 
    dice.superview.center = CGPointMake((self.view.frame.size.width - CGRectGetMaxX(imageBack.frame))/2 + rndValue + CGRectGetMaxX(imageBack.frame), dice.superview.center.y); 
}completion:^(BOOL finished){ 

}]; 

反正有我的價值觀..你可以把任何你想要有!

希望它有幫助