Given the coordinates of two rectangles on a coordinate plane, what would be the easiest way to find the coordinates of the intersecting rectangle of the two?
I am trying to do this programatically.
Given the coordinates of two rectangles on a coordinate plane, what would be the easiest way to find the coordinates of the intersecting rectangle of the two?
I am trying to do this programatically.
Working from Zwarmapapa's solution, you probably want to check that the rectangles actually overlap, and optionally that the overlap has a non-zero area.
When there is no overlap, the two coordinates will be reversed (top left will actually be bottom right and vice-versa).
If you want the rectangles with zero area (edge/corner intersection), change the two less than checks to less than or equal.
Rectangle r1 = rect1;
Rectangle r2 = rect2;
Rectangle intersectionRect = null;
int leftX = Math.max( r1.getX(), r2.getX() );
int rightX = Math.min( r1.getX() + r1.getWidth(), r2.getX() + r2.getWidth() );
int topY = Math.max( r1.getY(), r2.getY() );
int bottomY = Math.min( r1.getY() + r1.getHeight(), r2.getY() + r2.getHeight() );
if ( leftX < rightX && topY < bottomY ) {
intersectionRect = new Rectangle( leftX, topY, rightX-leftX, bottomY-topY );
} else {
// Rectangles do not overlap, or overlap has an area of zero (edge/corner overlap)
}
Just think logically, draw it in mspaint or something. I got the answer in less than 15 minutes.
Rectangle r1 = rect1; Rectangle r2 = rect2; int leftX = Math.max( r1.getX(), r2.getX() ); int rightX = Math.min( r1.getX()+r1.getWidth(), r2.getX()+r2.getWidth() ); int topY = Math.max( r1.getY(), r2.getY() ); int bottomY = Math.min( r1.getY()+r1.getHeight(), r2.getY()+r2.getHeight() ); Rectangle intersectionRect = new Rectangle( leftX, topY, rightX-leftX, bottomY-topY );
In order to simplify the problem, I will assume that the rectangles are orientated "straight up and down." By this I mean that each of the rectangles has an edge which is parallel to the x (or y) axis. Judging by the context, this should be a fair assumption. Let me know if this is not the case (in other words, what class is this for?) It might help to first graph the two rectangles whose coordinates are given. In the "simplest" case they will intersect in exactly two places.
The coordinates for some intersection will just be the point where "edge a" of "rectangle 1" intersects "edge x" of "rectangle 2." That is, the intersection point will have the x value of (edge a or x), and the y value of the other edge (since these rectangles are parallel to the axis the x or y value of an edge will be constant across that edge.) You know the values of these edges by the coordinates given for the corners of your original rectangles.
After drawing the rectangles this should be a fairly easy and straight-forward process to work through. If you are trying to write a computer program to do this for you it is slightly more complicated but follows the same logic. Hope this helps!