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