Determine a bounding rectangle around a diagonal line
Asked Answered
R

2

5

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.

Roseanneroseate answered 6/8, 2016 at 17:55 Comment(3)
It seems to be a mathematical (geometrical) questionLargo
I'm voting to close this question as off-topic because it is not about programming, but about geometry.Massy
This is about maths AND programming as maths formulae need to be translated into the relevant programming language, in this case Java. So not of topic for either maths or programming !Roseanneroseate
D
8
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
Duong answered 7/8, 2016 at 15:16 Comment(4)
how are you able to express this rectangle with 4 coordinates ... ?Aleph
@willywonkadailyblah: oooops, I answered for the AABB.Duong
@YvesDaoust, thanks for this. One question though, will this work no matter the order of the start and end points ? I mean by this, can the start point be greater than the end point - bottom right to top left ?Roseanneroseate
@Simon: this is something you can check by yourself.Duong
C
1

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

Celle answered 19/4, 2022 at 20:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.