Reputation: 625
I am having a problem with 2 rectangles intersection (one is bigger than other) in my android project. I used Rect.intersects(rect1,rect2) method, it works fine but I should know where it intersected. For example, rect1.right intersected with rect2.left etc. Is there any way to solve this problem?Example
I've written something like that to detect top or bottom. But it gives me mistakes by 2 or 5 pixels.
if (Rect.intersects(rect2,rect1)){
//rect1 is smaller one
if (rect1.exactCenterY()<rect2.exactCenterY() - rect2.height()/2||
rect1.exactCenterY()>rect.exactCenterY() + rect2.height()/2){
//It is top or bottom
doSomething();
}else{
doSomething();
}
}
I hope you guys will give me some advice or another way to solve it.
Upvotes: 0
Views: 866
Reputation: 625
Found it! Thanks for advices. But important thing that you should also handle intersection for corners of rectangle.
if(rect2.setIntersects(rect2,rect1)){
if(rect2.left!=rect1.left){
//do something
}else if(rect2.right!=rect1.right){
//do something
}// and so on
}
Upvotes: 1
Reputation: 80
If you are using Rectangle class:
int x = (int) rect1.intersection(rect2).getX();
int y = (int) rect1.intersection(rect2).getY();
the method intersection returns the intersection rectangle. Read out that rectangle. Hope this helps.
Upvotes: 1