Adding margin around a line segment

86 Views Asked by At

I have a line segment given by its two endpoints - $(x1, y1)$ and $(x2, y2)$. For given margin $m$, I need to find the polygon around the line with margin.

When the line segment is a horizontal or vertical line I can easily determine the coordinates of the surrounding polygon (rectangle). For example:

enter image description here

But when the given line has a slope, I'm stuck here.

enter image description here

How should I calculate the coordinates in this case without using trigonometric functions and division (i.e. I know I could use line equation to determine the points)? I need that accuracy.

Thanks in advance.

1

There are 1 best solutions below

0
On BEST ANSWER

It might be useful to parametrize your line as follows: $$ \left( \begin{matrix} x \\ y \end{matrix} \right) = \left( \begin{matrix} x_1 \\ y_1 \end{matrix} \right) + t\cdot \left( \begin{matrix} x_2-x_1 \\ y_2-y_1 \end{matrix} \right) \quad t\in [0,1] $$ If you take values of $t$ slightly smaller than $0$ or slightly larger than $1$, you get a slightly longer line. To describe the width use the normal vector $$ \left( \begin{matrix} y_1-y_2 \\ x_2-x_1 \end{matrix} \right) $$ So now the box is mathematically described by $$ \left( \begin{matrix} x \\ y \end{matrix} \right) = \left( \begin{matrix} x_1 \\ y_1 \end{matrix} \right) + t\cdot \left( \begin{matrix} x_2-x_1 \\ y_2-y_1 \end{matrix} \right)+s\cdot \left( \begin{matrix} y_1-y_2 \\ x_2-x_1 \end{matrix} \right) \quad t\in [-\varepsilon,1+\varepsilon], s \in [-\varepsilon, \varepsilon]. $$ If you want the offset to be $m$, you can choose $$ \varepsilon = \frac{m}{d}, $$ where $d$ is the length of your line.