检测两个ImageView之间的交集

时间:2014-08-07 09:34:09

标签: java android imageview intersect rect

我有两个ImageView,我想检测两个图像之间的交集。所以我决定在网上找到一个解决方案,我使用getDrawingRect绘制一个矩形,用ImageView包装。但是,我运行代码时遇到问题。两个imageView都不会相交,但Rect.Intersect返回true。总是如此,无论它们是否相交。 以下是我的代码。

两张图片之间的交点

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}

第一张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" />

第二个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" />

1 个答案:

答案 0 :(得分:4)

代码的问题在于用于在屏幕上获取ImageView矩形的函数不正确。请参阅getDrawingRect()文档:

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

因此,对于两个ImageView,它返回几乎相同的矩形,因为它返回'internal'rect。

要在屏幕上获取矩形,您需要使用getLocationInWindow()getLocationOnScreen()getLocalVisibleRect()。然后,您的代码可能采用以下方式(使用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();
}