Assume I have the following overlapping rectangles (\"a\" and \"b\"):
aaaaaaaa
aaaaccccbbbbb
aaaaccccbbbbb
aaaaccccbbbbb
bbbbbbbbb
bbbbbbbbb
The X coordinates of the overlap area of two rectangles can be found according to the following logic.
To find the Y coordinates, substitute Y for X in the last of the four assumptions, as well as in all of the three cases.
Assumptions:
A and B are rectangles (with their sides aligned along the X and Y axes),
each of the rectangles is defined by two points (xmin / ymin) – (xmax / ymax)
where xmin < xmax and ymin < ymax .
A.xmin < B.xmin
Case 1 — No overlap:
+--------+
|A |
| | +----+
| | |B |
| | +----+
| |
+--------+
A.xmin < A.xmax < B.xmin < B.xmax ⇒ No overlap.
Case 2 — Some overlap:
+--------+
|A |
| +--+-+
| |B | |
| +--+-+
| |
+--------+
A.xmin < B.xmin < A.xmax < B.xmax ⇒ Overlap X coordinates: B.xmin – A.xmax
Case 3 — Complete overlap:
+--------+
|A |
| +----+ |
| |B | |
| +----+ |
| |
+--------+
A.xmin < B.xmin < B.xmax < A.xmax ⇒ Overlap X coordinates: B.xmin – B.xmax
P.S.: You can actually further simplify this algorithm. The overlap X coordinates are always:
max(A.xmin, B.xmin) – min(A.xmax, B.xmax)
except when the second value is less than the first; that means that there is no overlap.