Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate the overlap area? [closed]

Tags:

math

There are two overlapping rectangles and I need to calculate the overlap area (width and height). Please this image:

enter image description here

like image 430
Joyq Avatar asked Aug 22 '11 06:08

Joyq


1 Answers

If rectangle r1 is at x1,y1 and have width w1,h1, and likewise rectangle r2 is at x2,y2 with width w2 and height h2, then you can find the left edge of the red region like (Assuming the widths and heights of both rectangles are positive so the positions are the bottom left corners):

left = max(x1, x2);

Similarly for the right, bottom and top:

right = min(x1 + w1, x2 + w2);
bottom = max(y1, y2);
top = min(y1 + h1, y2 + h2);

The size of the overlapping area is

height = top - bottom 
width = right - left. 

If either if these is negative, there is no overlap.

like image 100
Anders Forsgren Avatar answered Oct 09 '22 09:10

Anders Forsgren