Drawing rectangle between two points with arbitrary width

后端 未结 3 1774
被撕碎了的回忆
被撕碎了的回忆 2020-12-08 17:06

I\'m trying to draw a line between two (2D) points when the user swipes their finger across a touch screen. To do this, I plan on drawing a rectangle on every touch update b

3条回答
  •  -上瘾入骨i
    2020-12-08 17:24

    If I understand you correctly, you have two end points say A(x1,y1) and B(x2,y2) and an arbitrary width for the rectangle say w. I assume the end points will be just at the middle of the rectangle's shorter sides meaning the distance of the final rectangles corner coordinates would be w/2 to A and B.

    You can compute the slope of the line by;

    s1 = (y2 - y1) / (x2 - x1) // assuming x1 != x2

    The slope of the shorter sides is nothing but s2 = -1/s1.

    We have slope, we have distance and we have the reference points.

    We than can derive two equations for each corner point:

    For one corner closer to A

    C(x3,y3):

    (y3 - y1) / (x3 - x1) = s2 // by slope

    (y3 - y1)^2 + (x3 - x1)^2 = (w/2)^2 // by distance

    replacing (y3 - y1) by a and (x3 - x1) by b yields

    a = b * s2 // slope equation

    // replace a by b*s2

    b^2 * s2^2 + b^2 = (w/2)^2 // distance equaiton

    b^2 = (w/2)^2 / (s2^2+1)

    b = sqrt((w/2)^2 / (s2^2+1))

    we know w and s2 and hence compute b

    If b is known, we can deduce x3

    x3 = b + x1

    and a, as well

    a = b * s2

    and so y3

    y3 = b*s2 + y1

    we have one corner point C(x3,y3).

    To compute the other corner point closer to A, say D(x4,y4), the slope equation can be constructed as

    (y1 - y4) / (x1 - x4) = s2 and the calculations listed above should be applied.

    Other two corners can be calculated with the steps listed here replacing A(x1, y1) with B(x2,y2).

提交回复
热议问题