How to know if two images are intersect while one

2019-04-08 17:34发布

In my application, i am moving image around the screen by using onTouchListener.

I have another two images in the same view. My problem is that, when the moving image, touches any of the other images, i need to perform a certain action (that means if images are intersected, then do something).

How can this be achieved?.Please help me asap

Thanks in Advance.

3条回答
该账号已被封号
2楼-- · 2019-04-08 18:11

In onTouch with move action you can get rectangle bound of your moving images and another. Check if your moving rect intersect with another by intersect function like: Rect movingBound = new Rect(); Rect[] anotherImagesBound = new Rect[...]

get Rect bound by:

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

same with another imageView. loop in the anotherImagesBound and check :

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

Note: you must update movingBound in every touch action, but your another ImageView you should get once. Hope this help

查看更多
做自己的国王
3楼-- · 2019-04-08 18:20

You should be able to use Rect.intersects(Rect, Rect), like 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
} 

Reference is here.

查看更多
Bombasti
4楼-- · 2019-04-08 18:29

When you move your image in the onTouch listener, check for rectangle intersection between View a and View b using:

a.getLeft() <= b.getRight() &&
b.getLeft() <= a.getRight() &&
a.getTop() <= b.getBottom() &&
b.getTop() <= a.getBottom()
查看更多
登录 后发表回答