2

是否有一種簡單的方法來指定圖像是否應該在目標C中順時針或逆時針旋轉?我有一個帶針的車速表(反映汽車價格的設計) - 它運轉良好,除非針更靠近旋轉並且離開屏幕到另一側。我希望它總是逆時針旋轉到較低的數字,順時針旋轉到較高的數字。這裏是我的代碼段:CoreAnimation旋轉變換動畫方向

// figure out the minimum and maximum prices shown on the 
// speedometer 
float min = [_a.text floatValue] * 1000; 
float max = [_g.text floatValue] * 1000; 

// set calibration between number labels to be small or large 
int cal = SMALL_CALIBRATION; 
if ([_stickerPriceSetting floatValue] >= TRIGGERPRICE) 
    cal = LARGE_CALIBRATION; 

// set an animation duration of 1.5 seconds for the needle rotation 
[UIView beginAnimations:nil context:NULL]; 
[UIView setAnimationDuration:1.5]; 

// low prices (off speedometer) 
if (price < (min - cal)) 
    _needle.transform = CGAffineTransformMakeRotation(- M_PI/12); 

// price too high (off speedometer) 
else if (price > (max + cal)) 
    _needle.transform = CGAffineTransformMakeRotation(M_PI * 13/12); 

// need to have needle point to the price 
else { 
    float delta = (max - min); 
    float price_point = price - min; 
    _needle.transform = CGAffineTransformMakeRotation(price_point/delta * M_PI); 
} 

[UIView commitAnimations]; 

回答

0

我和車速表有同樣的問題。動畫transform-property時無法指定旋轉方向。它將始終以最短的方式。如果角度大於180度(第二次動畫在第一次完成後開始),我通過做2個動畫來解決問題。您必須注意正確的動畫時間,以使其動畫順暢。

+0

這對我很有幫助,除非我無法知道從原點到新點的角度是否會大於180度 - 除非有一個簡單的方法可以先找出角度針(UIView)目前在?我猜測我將不得不編寫一堆保存舊價格的代碼,並將這些代碼納入針的運動。 – 2012-02-05 20:51:19

2

您可以通過動畫的層屬性transform.rotation做到這一點:

// figure out the minimum and maximum prices shown on the 
// speedometer 
float min = [_a.text floatValue] * 1000; 
float max = [_g.text floatValue] * 1000; 

// set calibration between number labels to be small or large 
int cal = SMALL_CALIBRATION; 
if ([_stickerPriceSetting floatValue] >= TRIGGERPRICE) 
    cal = LARGE_CALIBRATION; 

CGFloat angle; 
if (price < min - cal) 
    angle = -M_PI/12; 
else if (price > max + cal) 
    angle = M_PI * 13/12; 
else 
    angle = M_PI * (price - min)/(max - min); 

[UIView animateWithDuration:1.5 animations:^{ 
    [(id)_needle.layer setValue:[NSNumber numberWithFloat:angle] 
     forKeyPath:@"transform.rotation"]; 
}]; 

如果導入QuartzCore/QuartzCore.h你不會需要(id)演員。