4

在我的應用程序中,我使用onTouchListener在屏幕上移動圖像。如何知道在android中移動一張圖片時兩張圖片是否相交?

我在同一視圖中有另外兩個圖像。 我的問題是,當運動圖像觸及任何其他圖像時,我需要執行某個動作 (即如果圖像相交,則執行某些操作)。

如何才能實現這一目標?。請幫我儘快

在此先感謝。

+0

爲什麼不使用單獨的觸摸監聽器? – k0sh

回答

12

你應該能夠使用Rect.intersects(Rect, Rect),像這樣的例子:

Rect myViewRect = new Rect(); 
myView.getHitRect(myViewRect); 

Rect otherViewRect1 = new Rect(); 
otherView1.getHitRect(otherViewRect1); 

Rect otherViewRect2 = new Rect(); 
otherView2.getHitRect(otherViewRect2); 

if (Rect.intersects(myViewRect, otherViewRect1)) { 
    // Intersects otherView1 
} 

if (Rect.intersects(myViewRect, otherViewRect2)) { 
    // Intersects otherView2 
} 

參考號是here

+0

感謝您的replay.It爲我工作。 – user2681425

+0

@ user2681425:這不適用於我的情況。你能用解決方案更新你的問題嗎? –

0

當你將圖像中的onTouch監聽,檢查查看和瀏覽之間的矩形交集b。使用:

a.getLeft() <= b.getRight() && 
b.getLeft() <= a.getRight() && 
a.getTop() <= b.getBottom() && 
b.getTop() <= a.getBottom() 
1

在帶移動動作的onTouch中,您可以獲得運動圖像的矩形邊界和另一個。通過相交函數檢查你的移動矩形是否與另一個相交: Rect movingBound = new Rect();

Rect movingBound = new Rect(); 
movingImage.getHitRect(movingBound); 

同另一個ImageView的: 矩形[] anotherImagesBound =新矩形[...]

得到矩形的約束。 循環在anotherImagesBound和檢查:

if (anotherImagesBound[index].intersect(movingBound)){ 
    // do something here 
} 

注意:你必須在每個觸摸動作更新movingBound,但你的另一個ImageView的你應該得到一次。 希望這個幫助

相關問題