[java] How to detect OverLapping ImageIcons

Started by
2 comments, last by harveypekar 17 years, 4 months ago
Hey, Is there a way to find out if an Imageicon is overlapping another imageicon,not just if they have the same x and y position but if they touch each other at all. Thanks
Advertisement
I don't know of any direct methods you can use, but you could build some java.awt.Rectangle 's from their dimensions and use the contains(), intersects() methods (Or calculate it yourself :) ).
Hey there,

the way I detect overlapping rectangles (which is basically your problem) is by detecting if they are NOT intersecting. THis would give you following method:



public static boolean isIntersecting(int x1, int y1, int w1, int h1, int x2, int y2, int w2, int h2){

//w and h are width and height

if(x2 > x1 + w1){
return false; //first rectangle is too much to the left
}

if(x1 > x2 + w2){
return false; //first rectangle is too much to the right
}

if(y2 > y1 + h1){
return false; //first rectangle is too low
}

if(y1 > y2 + h2){
return false; //first rectangle is too high
}

return true//it could only be intersecting

}

I still have to test this code, but it should work
If somebody knows a more efficient way, I would like to hear about it.
Hey there,

the way I detect overlapping rectangles (which is basically your problem) is by detecting if they are NOT intersecting. THis would give you following method:



public static boolean isIntersecting(int x1, int y1, int w1, int h1, int x2, int y2, int w2, int h2){

//w and h are width and height

if(x2 > x1 + w1){
return false; //first rectangle is too much to the left
}

if(x1 > x2 + w2){
return false; //first rectangle is too much to the right
}

if(y2 > y1 + h1){
return false; //first rectangle is too low
}

if(y1 > y2 + h2){
return false; //first rectangle is too high
}

return true//it could only be intersecting

}

I still have to test this code, but it should work
If somebody knows a more efficient way, I would like to hear about it.

This topic is closed to new replies.

Advertisement