2011-01-13 78 views
1

我有一個按鈕,我在UIImageView上添加。當用戶觸摸屏幕 時,UIImageView將旋轉,我想知道是否有方法在旋轉完成後獲取按鈕的新位置。旋轉UIView後檢查UIButton的位置

現在,我讓所有的時間用這種方法原來的位置:

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { 

    NSLog(@"Xposition : %f", myButton.frame.origin.x); 
    NSLog(@"Yposition : %f", myButton.frame.origin.y); 

} 

感謝,

回答

6

這是一個棘手的問題。參考UIView關於幀屬性的文檔,它指出:

警告:如果transform屬性不是標識轉換,則此屬性的值是未定義的,因此應該忽略。

所以訣竅是找到一個解決方法,它取決於你確切的需要。如果你只需要一個近似值,或者如果你的旋轉總是90度的倍數,那麼CGRectApplyAffineTransform()函數可能工作得很好。將它傳遞給感興趣的UIButton的(未轉換的)框架,以及按鈕的當前轉換,它會給你一個轉換矩形。請注意,由於rect被定義爲原點,寬度和高度,因此無法定義邊長不平行於屏幕邊的矩形。在不平行的情況下,它將返回旋轉矩形的最小可能的邊界矩形。

現在,如果你需要知道一個或全部轉化點的精確座標,我已經寫代碼之前計算它們,但它是一個有點更復雜:

- (void)computeCornersOfTransformedView:(UIView*)transformedView relativeToView:(UIView*)parentView { 
    /* Computes the coordinates of each corner of transformedView in the coordinate system 
    * of parentView. Each is corner represented by an independent CGPoint. Doesn't do anything 
    * with the transformed points because this is, after all, just an example. 
    */ 

    // Cache the current transform, and restore the view to a normal position and size. 
    CGAffineTransform cachedTransform = transformedView.transform; 
    transformedView.transform = CGAffineTransformIdentity; 

    // Note each of the (untransformed) points of interest. 
    CGPoint topLeft = CGPointMake(0, 0); 
    CGPoint bottomLeft = CGPointMake(0, transformedView.frame.size.height); 
    CGPoint bottomRight = CGPointMake(transformedView.frame.size.width, transformedView.frame.size.height); 
    CGPoint topRight = CGPointMake(transformedView.frame.size.width, 0); 

    // Re-apply the transform. 
    transformedView.transform = cachedTransform; 

    // Use handy built-in UIView methods to convert the points. 
    topLeft = [transformedView convertPoint:topLeft toView:parentView]; 
    bottomLeft = [transformedView convertPoint:bottomLeft toView:parentView]; 
    bottomRight = [transformedView convertPoint:bottomRight toView:parentView]; 
    topRight = [transformedView convertPoint:topRight toView:parentView]; 

    // Do something with the newly acquired points. 
} 

請原諒任何輕微代碼中的錯誤,我寫在瀏覽器中。不是最有用的IDE ...

+3

這很令人驚訝,你可以編寫像IN IN BROWSER這樣的代碼。哇!我不會越過這個「空白」,因爲我忘記了如何拼寫,並且必須從另一個項目中複製和粘貼。 – Fattie 2011-01-13 08:04:31