Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the points of intersection from 2 rectangles

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.

like image 740
NoSense Avatar asked Nov 03 '13 12:11

NoSense


People also ask

How do you find the point of intersection of two rectangles?

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.)

How do you find the intersection of two rectangles in Java?

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.

How do you find the intersection of two rectangles in Python?

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.


1 Answers

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.

like image 135
AnT Avatar answered Oct 01 '22 11:10

AnT