Let say that we have two rectangles, defined with their bottom-left and top-right corners. For example: rect1 (x1, y1)(x2, y2) and rect2 (x3, y3)(x4, y4). I'm trying to find the coordinates(bottom-left and top-right) of the intersected rectangle.
Any ideas, algorithm, pseudo code, would be greatly appreciated.
p.s. I found similar questions but they check only if 2 rectangle intersect.
In order to check that two rectangles intersect all that's needed is x1 < x4 && x3 < x2 && y1 < y4 && y3 < y2 . That's it. (I used strict inequalities to exclude touching rectangles.)
Rectangle rect1 = new Rectangle(100, 100, 200, 240); Rectangle rect2 = new Rectangle(120, 80, 80, 120); Rectangle intersection = rect1. intersection(rect2); say (x1, y1), (x2, y2) are bottom-left and bottom-right corners of Rect1 respectively, (x3, y3), (x4, y4) are those of Rect2.
Suppose there is a rectangle that is represented as a list [x1, y1, x2, y2], where (x1, y1) is the coordinates of its bottom-left corner, and (x2, y2) is the coordinates of its top-right corner. Now two rectangles overlap if the area of their intersection is positive.
If the input rectangles are normalized, i.e. you already know that x1 < x2
, y1 < y2
(and the same for the second rectangle), then all you need to do is calculate
int x5 = max(x1, x3); int y5 = max(y1, y3); int x6 = min(x2, x4); int y6 = min(y2, y4);
and it will give you your intersection as rectangle (x5, y5)-(x6, y6)
. If the original rectangles do not intersect, the result will be a "degenerate" rectangle (with x5 >= x6
and/or y5 >= y6
), which you can easily check for.
P.S. As usual, small details will depend on whether you have to consider touching rectangles as intersecting.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With