If the input rectangles are normalized, i.e. you already know that x1 < x2
, y1 < y2
(and the same for the second rectangle), then all you need to do is calculate
int x5 = max(x1, x3);
int y5 = max(y1, y3);
int x6 = min(x2, x4);
int y6 = min(y2, y4);
and it will give you your intersection as rectangle (x5, y5)-(x6, y6)
. If the original rectangles do not intersect, the result will be a "degenerate" rectangle (with x5 >= x6
and/or y5 >= y6
), which you can easily check for.
P.S. As usual, small details will depend on whether you have to consider touching rectangles as intersecting.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…