How to know if two images are intersect while one image moving in android?

偶尔善良 提交于 2019-12-04 08:27:57

You should be able to use Rect.intersects(Rect, Rect), like this example:

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
} 

Reference is here.

In onTouch with move action you can get rectangle bound of your moving images and another. Check if your moving rect intersect with another by intersect function like: Rect movingBound = new Rect(); Rect[] anotherImagesBound = new Rect[...]

get Rect bound by:

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

same with another imageView. loop in the anotherImagesBound and check :

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

Note: you must update movingBound in every touch action, but your another ImageView you should get once. Hope this help

When you move your image in the onTouch listener, check for rectangle intersection between View a and View b using:

a.getLeft() <= b.getRight() &&
b.getLeft() <= a.getRight() &&
a.getTop() <= b.getBottom() &&
b.getTop() <= a.getBottom()
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!