Say we represent rectangles as a pair of x, y coordinate pairs: x1, y1 for the upper left and x2, y2 for the lower left corner. Suppose also that the y coordinate increases down and the x coordinates increase from left to right.
Now suppose that the rectangle formed by the union of A and B (according to your definition of a union) is a rectangle U.
So,
U.x1=min(A.x1,B.x1), U.y1=min(A.y1,B.y2)
Now that we have a large rectangle U, we can use it to calculate the smaller right and lower rectangles that should be added to (left / top rectangle) to make it U. Lets call them Rt and Bot.
(This time, I assume that A is the top left rectangle if it is not swapping A and B. We also assume that the layout will look like the layout of your image. If it is not, you can easily adapt this).
Rt.x1=A.x2, Rt.y1=A.y1 Rt.x2=A.x2, Rt.y2=B.y2 Bot.x1=A.x1, Bot.y1=A.y2 Bot.x2=A.x2, Bot.y2=B.y2
MAK
source share