2009-07-13 84 views
0

在iPhone上,如何使用手指觸摸在中心點周圍實現旋轉圖像?如何通過手指觸摸自動圍繞中心點旋轉圖像

就像輪子一樣,如果你將手指放在iPhone屏幕上,然後突然移動,那麼圖像就像輪子一樣圍繞中心點旋轉,過了一會兒,它變得越來越慢,最後停下來。

誰可以幫助給一些代碼片段(Object-C)或一些建議?

回答

1

我會使用仿射變換 - 你可以使用transform屬性爲任何圖層或UI元素分配變換。

您可以使用CGAffineTransform CGAffineTransformMakeRotation( CGFloat angle)創建一個旋轉變換,它將返回一個旋轉元素的變換。默認旋轉應該在中心點附近。

請注意,旋轉被限制在360度,所以如果你想旋轉比這更多的東西(比如720度) - 你必須將旋轉分成幾個序列。

您也可以找到this SO article

1

視圖或圖層的transform屬性可用於旋轉顯示在其中的圖像。就旋轉部分而言,您只需使用touchesBegan,touchesMoved和touchesEnded跟蹤觸摸的位置和移動。

使用觸摸更新之間的距離和時間來計算速度,並使用它來設置旋轉速度。一旦開始圖像旋轉,定期更新位置(也許使用NSTimer),並將旋轉速度降低一些常數。

2

我昨天正在用「旋轉瓶子」-app。在窗口中,我有一個ImageView和一個瓶子,用來響應觸摸並旋轉用戶滑動手指的方式。我努力讓我的ImageView在觸摸事件中旋轉(TouchesBegan,Touchesoved,TouchesEnd)。我在TouchesMoved中使用這段代碼來找出巫婆中的角度來旋轉圖像。

public override void TouchesMoved (NSSet touches, UIEvent evt) 
{  
    PointF pt = (touches.AnyObject as UITouch).LocationInView(this); 

    float x = pt.X - this.Center.X; 
    float y = pt.Y - this.Center.Y; 
    double ang = Math.Atan2(x,y); 

    // yada yada, rotate image using this.Transform 
} 

這很重要! 當ImageView旋轉時,即使x座標變化。因此,觸摸相同的區域會在pt和prePt點給我不同的值。經過一番思考,寫作和閱讀後,我想出了一個簡單的解決方案。 ImageView的「SuperView」屬性。

PointF pt = (touches.AnyObject as UITouch).LocationInView(this.SuperView); 

有到位的小改動,感覺就容易得多,沒有我可以使用UITouch-metohs LocationInView和PreviousLocationInView並獲得合適的x & y座標。她是我的代碼的一部分。

float deltaAngle; 

public override void TouchesMoved (NSSet touches, UIEvent evt) 
{ 
    PointF pt = (touches.AnyObject as UITouch).LocationInView(this.Superview); 

    float x = pt.X - this.Center.X; 
    float y = pt.Y - this.Center.Y; 
    float ang = float.Parse(Math.Atan2(dx,dy).ToString()); 


    //do the rotation 
    if (deltaAngle == 0.0) { 
     deltaAngle = ang; 
    } 
else 
    { 
     float angleDif = deltaAngle - ang; 
     this.Transform = CGAffineTransform.MakeRotation(angleDif); 
    } 
} 

希望能幫助某人花費數小時的時間來弄清楚如何讓怪物旋轉瓶子! :)