1

I have two ImageViews and I want to detect the intersection between the two images. So I decided to find a solution online, I'm using getDrawingRect to draw a rectangle, wrapping with the ImageView. However, I have a problem when I run the codes. Both imageViews don't get intersect but Rect.Intersect return true. Always true, no matter they got intersect or not. Below is my codes.

Intersection between two images

Rect rc1 = new Rect();
rc1.left = arrow.getLeft();
rc1.top = arrow.getTop();
rc1.bottom = arrow.getBottom();
rc1.right = arrow.getRight();
arrow.getDrawingRect(rc1);

Rect rc2 = new Rect();
rc2.left = view.getLeft();
rc2.top = view.getTop();
rc2.bottom = view.getBottom();
rc2.right = view.getRight();
view.getDrawingRect(rc2);

if (Rect.intersects(rc1,rc2))
{//intersect!}
else{//not intersect}

First ImageView

<ImageView
android:id="@+id/needle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="@+id/spinnerFrame"
android:layout_centerHorizontal="true"
android:src="@drawable/arrow_top" />

Second ImageView

<ImageView
android:id="@+id/letter_a"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/needle"
android:layout_marginLeft="-10dp"
android:layout_marginTop="-10dp"
android:layout_toRightOf="@+id/needle"
android:scaleType="matrix"
android:src="@drawable/letter_a" />
AndroidBeginner
  • 153
  • 2
  • 12
  • Maybe it is a duplicated question. See http://stackoverflow.com/questions/115426/algorithm-to-detect-intersection-of-two-rectangles – Paulo Aug 07 '14 at 09:54

1 Answers1

4

The problem with your code is in incorrect function used to obtain ImageView rectangle on the screen. Refer to getDrawingRect() docs:

Return the visible drawing bounds of your view. Fills in the output rectangle with the values from getScrollX(), getScrollY(), getWidth(), and getHeight().

So, for both ImageView it returns almost the same rectangles, because it returns 'internal' rect.

To obtain rectangle on the screen, you need to use getLocationInWindow(), getLocationOnScreen() or getLocalVisibleRect(). Then, your code might look the following way (using getLocalVisibleRect()):

// Location holder
final int[] loc = new int[2];

mArrowImage.getLocationInWindow(loc);
final Rect rc1 = new Rect(loc[0], loc[1],
        loc[0] + mArrowImage.getWidth(), loc[1] + mArrowImage.getHeight());

mLetterImage.getLocationInWindow(loc);
final Rect rc2 = new Rect(loc[0], loc[1],
        loc[0] + mLetterImage.getWidth(), loc[1] + mLetterImage.getHeight());

if (Rect.intersects(rc1,rc2)) {
    Log.d(TAG, "Intersected");
    Toast.makeText(this, "Intersected!", Toast.LENGTH_SHORT).show();
} else {
    Log.d(TAG, "NOT Intersected");
    Toast.makeText(this, "Not Intersected!", Toast.LENGTH_SHORT).show();
}
sandrstar
  • 12,503
  • 8
  • 58
  • 65