How to calculate the overlap area? [closed]
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 11 years ago.
Improve this questionThere are two overlapping rectangles and I need to calculate the overlap area (width and height). Please this image:
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.
精彩评论