0

I'm developing a test game with some imageviews on the screen.

with the finger, I am moving another imageview.

I want to detect when the imageview moved by the finger has touched another imageview.

Which is the best way to achieve it? I can't find info about it on Google.

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
NullPointerException
  • 36,107
  • 79
  • 222
  • 382

2 Answers2

3

I'll answer the general question - find out when two views overlap:


private boolean viewsOverlap(View v1, View v2) {
    int[] v1_coords = new int[2];
    v1.getLocationOnScreen(v1_coords);
    int v1_w = v1.getWidth();
    int v1_h = v1.getHeight();
    Rect v1_rect = new Rect(v1_coords[0], v1_coords[1], v1_coords[0] + v1_w, v1_coords[1] + v1_h);

    int[] v2_coords = new int[2];
    v2.getLocationOnScreen(v1_coords);
    int v2_w = v2.getWidth();
    int v2_h = v2.getHeight();
    Rect v2_rect = new Rect(v2_coords[0], v2_coords[1], v2_coords[0] + v2_w, v2_coords[1] + v2_h);

    return v1_rect.intersect(v2_rect) || v1_rect.contains(v2_rect) || v2_rect.contains(v1_rect);
}


My trigonometry is a little shaky these days so I'm not sure about this part:

OVERLAP ==  v1_rect.intersect(v2_rect) || v1_rect.contains(v2_rect) || v2_rect.contains(v1_rect);


Double check me. Good luck.


Gilad Haimov
  • 5,767
  • 2
  • 26
  • 30
  • 1
    Hi, thanks but that creates a rectangle, and my images are not rectangles, are pngs with rounded pictures, like clouds, or balls. So, this collision strategy is giving me a failure, because it is giving me collision when the corner of the imageview has touched the corner of the other imageview, but the bitmaps inside the imageviews are not bening touched... Can this be solved? – NullPointerException Jul 06 '14 at 23:22
  • @AndroidUser99 have you found the solution ? – Usman Mar 28 '15 at 04:46
0

Try using the intersect method of class Rect:

https://stackoverflow.com/a/19086884/3249477

Community
  • 1
  • 1
Simas
  • 43,548
  • 10
  • 88
  • 116
  • The question was also different than yours. Did you try this? – Simas Jul 06 '14 at 21:38
  • Hi, thanks but that creates a rectangle, and my images are not rectangles, are pngs with rounded pictures, like clouds, or balls. So, this collision strategy is giving me a failure, because it is giving me collision when the corner of the imageview has touched the corner of the other imageview, but the bitmaps inside the imageviews are not bening touched... Can this be solved? – NullPointerException Jul 06 '14 at 23:25