【问题标题】:Detect intersection between two ImageView检测两个 ImageView 之间的交集
【发布时间】:2014-08-12 20:04:54
【问题描述】:

我有两个 ImageView,我想检测两个图像之间的交集。于是决定在网上找个解决办法,我用getDrawingRect画一个矩形,用ImageView包裹。但是,我在运行代码时遇到了问题。两个 imageViews 都没有相交,但 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
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" />

【问题讨论】:

标签: java android imageview intersect rect


【解决方案1】:

您的代码的问题在于用于在屏幕上获取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,它返回几乎相同的矩形,因为它返回“内部”矩形。

要获取屏幕上的矩形,需要使用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();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-04-27
    • 2016-01-20
    • 2012-07-08
    • 2018-08-23
    • 2018-06-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多