当一个图像在android中移动时,如何知道两个图像是否相交?

时间:2013-08-23 08:25:59

标签: android android-imageview android-image ontouchlistener android-gesture

在我的应用程序中,我使用onTouchListener在屏幕上移动图像。

我在同一视图中有另外两张图片。 我的问题是,当运动图像触摸任何其他图像时,我需要执行某个动作 (这意味着如果图像相交,那么就做点什么)。

如何实现这一目标?。请尽快帮助我

先谢谢。

3 个答案:

答案 0 :(得分:14)

您应该可以使用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

答案 1 :(得分:1)

在带有移动动作的onTouch中,您可以获得移动图像的矩形边界和另一个。通过交叉函数检查移动的矩形是否与另一个相交,如: Rect movingBound = new Rect(); Rect [] anotherImagesBound = new Rect [...]

获取Rect绑定:

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

与另一个imageView相同。 在anotherImagesBound中循环并检查:

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

注意:您必须在每次触摸动作中更新movingBound,但您应该获得另一个ImageView。 希望这个帮助

答案 2 :(得分:0)

在onTouch侦听器中移动图像时,请使用以下方法检查View a和View b之间的矩形交集:

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