Given the coordinates of the top left corners of two rectangles (x1
, y1
), (x2
, y2
), their respective widths and heights (w1
, h1
), (w2
, h2
) (They may or may not overlap). How do I find the coordinates of the top left corner (x3
, y3
) and the width and height (w3
, h3
) of the minimum bounding rectangle that encloses the 2 given rectangles. The widths and heights of the two rectangles are always parallel to the xy axis respectively. x increases from left to right and y increases from top to bottom.
For example, if
x1
= 2, y1
= -1, w1
= 3, h1
= 6
x2
= -1, y2
= 3, w2
= 8, h2
= 3
then
x3
= -1, y3
= -1, w3
= 8, h3
= 7
I can only find x3
and y3
but not w3
and h3
.
x3 = min(x1, x2)
, y3 = min(y1, y2)
One way to define an axis-aligned rectangle is to list its four coordinates (xmin, xmax, ymin, ymax)
.
If you have two rectangles:
R1 (xmin1, xmax1, ymin1, ymax1)
R2 (xmin2, xmax2, ymin2, ymax2)
Then the minimum axis-aligned bounding rectangle is of course given by coordinates:
R (min(xmin1,xmin2), max(xmax1,xmax2), min(ymin1,ymin2), max(ymax1,ymax2))
You can switch easily between the (xmin, xmax, ymin, ymax)
and the (xtopleft, ytopleft, width, height)
representations:
(xmin, xmax, ymin, ymax) = (xtopleft, ytopleft, xtopleft+width, ytopleft+height)
(xtopleft, ytopleft, width, height) = (xmin, ymin, xmax-xmin, ymax-ymin)