Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two Rectangles intersection

I have two rectangles characterized by 4 values each :

Left position X, top position Y, width W and height H:

X1, Y1, H1, W1 X2, Y2, H2, W2 

Rectangles are not rotated, like so:

+--------------------> X axis | |    (X,Y)      (X+W, Y) |    +--------------+ |    |              | |    |              | |    |              | |    +--------------+ v    (X, Y+H)     (X+W,Y+H)  Y axis 

What is the best solution to determine whether the intersection of the two rectangles is empty or not?

like image 674
Majid Laissi Avatar asked Nov 15 '12 01:11

Majid Laissi


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

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.

Do you check if two rectangles overlap with each other?

Two rectangles do not overlap if one of the following conditions is true. 1) One rectangle is above top edge of other rectangle. 2) One rectangle is on left side of left edge of other rectangle.


1 Answers

if (X1+W1<X2 or X2+W2<X1 or Y1+H1<Y2 or Y2+H2<Y1):     Intersection = Empty else:     Intersection = Not Empty 

If you have four coordinates – ((X,Y),(A,B)) and ((X1,Y1),(A1,B1)) – rather than two plus width and height, it would look like this:

if (A<X1 or A1<X or B<Y1 or B1<Y):     Intersection = Empty else:     Intersection = Not Empty 
like image 105
Tao Peng Avatar answered Sep 21 '22 08:09

Tao Peng