'Determine a bounding rectangle around a diagonal line

A user will define a line on screen which will have, when drawn, a given thickness (or width).

I now need to be able to determine the coordinates of a bounding rectangle around this. enter image description here

I have the coordinates A and B, along with the line thickness (W).

How can I calculate the coordinates A1, A2, B1 and B2.

I searched but was unable to find a question corresponding to this already asked.



Solution 1:[1]

Dx= Xb - Xa
Dy= Yb - Ya
D= sqrt(Dx * Dx + Dy * Dy)
Dx= 0.5 * W * Dx / D
Dy= 0.5 * W * Dy / D

This computes (Dx, Dy) a vector of length W/2 in the direction of AB. Then (-Dy, Dx) is the perpendicular vector.

Xmin = min(Xa, Xb) - abs(Dy) 
Xmax = max(Xa, Xb) + abs(Dy)
Ymin = min(Ya, Yb) - abs(Dx)
Ymax = max(Ya, Yb) + abs(Dx)

Update:

I answered for the AABB by mistake.

For the four corners of the stroke

Xa - Dy, Ya + Dx
Xa + Dy, Ya - Dx
Xb - Dy, Yb + Dx
Xb + Dy, Yb - Dx

Solution 2:[2]

Here I am adding the python solution for @Yves Daoust answer

    import numpy as np
    import matplotlib.pyplot as plt
    import matplotlib.patches as patches 

    fig = plt.figure()
    ax = fig.add_subplot(111)

    pt1 = np.array([23, 45])
    pt2 = np.array([34, 56])

    delta = pt2 - pt1 
    distance = np.linalg.norm(delta)
    width = 20.0
    rect_x = 0.5*width*delta[0]/distance
    rect_y = 0.5*width*delta[1]/distance

    r1 = (pt1[0]-rect_y, pt1[1]+rect_x)
    r2 = (pt1[0] + rect_y, pt1[1]- rect_x)
    r3 = (pt2[0]-rect_y, pt2[1]+rect_x)
    r4 = (pt2[0] + rect_y, pt2[1]- rect_x)


    plt.xlim(0, 100)
    plt.ylim(0, 100)
    ax.axline((pt1[0], pt1[1]), (pt2[0], pt2[1]), linewidth=1, color='r')
    points = [r1, r2, r4, r3]
    rect = patches.Polygon(points, linewidth=1, edgecolor='r')
    ax.add_patch(rect)
    ax.scatter(x=r1[0], y=r1[1])
    ax.scatter(x=r2[0], y=r2[1])
    ax.scatter(x=r3[0], y=r3[1])
    ax.scatter(x=r4[0], y=r4[1])
    plt.show()

enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 GPrathap