[Math] Get the four corners of a rectangle

analytic geometrygeometrytransformation

Illustration of the problem

I have a boundary given ($xMin$, $yMin$, $xMax$, $yMax$) and the two points of a reference line of a rectangle. The begin point is at $(x_b, y_b)$ and the end point is at $(x_e, y_e)$. This reference line tells the rectangle's angle and length.

If we transform the reference line so that it is parallel to the x-axis and its begin point is on the left of the end point, the outer side is above the inner side.

Illustration of the transformed sample

I need to get the four corners of the rectangle. The parallel sides is then categorized as outer side or inner side. So the four sides is represented by:

  • begin point of outer side: $(x_{ob}, y_{ob})$
  • begin point of inner side: $(x_{ib}, y_{ib})$
  • end point of outer side: $(x_{oe}, y_{oe})$
  • end point of inner side: $(x_{ie}, y_{ie})$

The width can now be computed as distance between the two begin or end points.

The perpendicular sides' slope is negative reciprocal of the reference line's slope: $$m=-\frac{x_e-x_b}{y_e-y_b}$$

The begin side has equation of (eq1): $$y=-\frac{x_e-x_b}{y_e-y_b}(x-x_b)+y_b$$
which is the same for the end side (eq2): $$y=-\frac{x_e-x_b}{y_e-y_b}(x-x_e)+y_e$$

After this, I am lost to what to do next. I know that I need to use the boundary values to substitute from eq1 and eq2.

Best Answer

Assume that the reference line isn’t parallel to any edge (in which case the bounding rectangle is the rectangle). Consider the case $x_b<x_e$, $y_b<y_e$. Let $\Delta x=x_e-x_b$ and $\Delta y=y_e-y_b$. Then, from inspection of the corresponding picture, the four corners of the rectangle can be seen to be $$\begin{align} ib &= (x_{max}-\Delta x, y_{min}) \\ ie &= (x_{max},y_{min}+\Delta y) \\ ob &= (x_{min},y_{max}-\Delta y) \\ oe &= (x_{min}+\Delta x,y_{max}). \end{align}$$ (Note that these formulas also work for $\Delta x>0$, $\Delta y=0$.)

The other three cases can either be handled separately in a similar manner, or by permuting the given values (i.e., by rotating through a suitable multiple of $\frac\pi2$), applying the above formula, and finally reversing the permutation.

Related Question