How to find out if two images intersect when one image moves in android?

In my application, I move the image around the screen using onTouchListener .

I have two more images in one view. My problem is that when a moving image touches any other image, I need to perform a certain action (this means that if the images intersect, then do something).

How can this be achieved? Please help me as soon as possible.

Thanks at Advance.

+4
source share
3 answers

You can use Rect.intersects(Rect, Rect) , as in 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 } 

Link here .

+12
source

In onTouch with a move action, you can get a rectangle associated with moving images, and another. Check if your straight lines intersect with each other using the intersection function, for example: Rect movingBound = new Rect (); Rect [] anotherImagesBound = new Rect [...]

get Rect bound by:

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

same with another image. loop in anotherImagesBound and check:

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

Note. You should update moveBound every time you touch, but you should get your other ImageView once. We hope for this help.

+1
source

When you move the image in the onTouch receiver, check the intersection of the rectangle between View a and View b using:

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

Source: https://habr.com/ru/post/1498555/


All Articles