2011-08-30 50 views
0

我移動我的UIImageView與層周圍的屏幕。在某些時候,我試圖使用imageView.frame.origin.x檢索移動的imageView的x和y座標,我接收到的原始座標不是移動後的新座標。如何正確獲取X和Y?UIImageView XY座標與層移動


這裏是我的代碼:

UIImageView *imageView = [[UIImageView alloc] initWithFrame:rect]; 
imageView.animationImages = [NSArray arrayWithArray:imgNameArr];  
imageView.animationDuration = 2; 
    imageView.animationRepeatCount = 0; 
    [imageView startAnimating]; 
    [self.view addSubview:imageView]; 
CAKeyframeAnimation *pathAnimation = [CAKeyframeAnimation animationWithKeyPath:@"position"]; 
pathAnimation.duration = speed; 
pathAnimation.calculationMode = kCAAnimationPaced; 
pathAnimation.fillMode = kCAFillModeForwards; 
pathAnimation.removedOnCompletion = NO; 
CGMutablePathRef pointPath = CGPathCreateMutable(); 
CGPathMoveToPoint(pointPath, NULL, rect.origin.x, rect.origin.y); 
    CGPathAddLineToPoint(pointPath, NULL, x, y); 
pathAnimation.path = pointPath; 
CGPathRelease(pointPath); 
[imageView.layer addAnimation:pathAnimation forKey:[NSString stringWithFormat:@"pathAnimation%@",objId]]; 
[imageView release]; 
+1

你可以加入一段代碼嗎?你在調用setNeedsLayout還是layoutIfNeeded? – bryanmac

+0

信息太少。如何發佈一些代碼? –

+0

已發佈我的回覆對這段代碼是正確的。在UIImageView的中心設置一個動畫,而不是它的圖層位置。否則'框架'是未定義的。 – Tommy

回答

0

UIView documentationframe屬性:

警告:如果變換屬性不是恆等變換,在此 值屬性是未定義的,因此應該忽略。

如果調整視圖的層的transformaffineTransform性能的frame屬性也變得不確定(這實際上是當您設置的UIView會改變我們的變換)。在Cocoa Touch中,轉換是在合成器合成時應用的。目前,當應用變換時看起來似乎是原始框架,好像沒有變換,但是由於文檔說它是未定義的,所以不要依賴它。

如果您只是移動視圖而沒有其他轉換,我建議您使用視圖的center屬性而不是應用轉換。這將正確更新您的框架。根據經驗證據,UIKit似乎也足夠聰明,與應用變換相比,僅調整中心並沒有任何性能下降。

+0

我必須使用圖層,因爲我的路徑非常複雜。 – Vad

+0

然後你有沒有試過讀回'layer.position'屬性?動畫後應該是正確的。它甚至可能完全值得放棄框架屬性 - 最初設置你的視圖,以便它具有正確的大小,並且在(0,0)處,然後通過layer.position完成其餘部分。 – Tommy

+0

是的,我最近嘗試所有 - layer.frame,layer.bounds和layer.position - 一切指向原始位置 – Vad