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. |
|||||||||||
|
|
You can think of an axis-aligned rectangle as the set of points $(x,y) \in \mathbb{R}^2$ such that $x_1 \le x \le x_2$ and $y_1 \le y \le y_2$. What can you say about the intersection of two such sets? |
|||
|
|
|
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! |
|||
|
|
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 ); |
|||
|
|