Drawing rectangle between two points with arbitrary width

后端 未结 3 1785
被撕碎了的回忆
被撕碎了的回忆 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条回答
  •  长情又很酷
    2020-12-08 17:26

    Calculate a vector between start and end points

    V.X := Point2.X - Point1.X;
    V.Y := Point2.Y - Point1.Y;
    

    Then calculate a perpendicular to it (just swap X and Y coordinates)

    P.X := V.Y; //Use separate variable otherwise you overwrite X coordinate here
    P.Y := -V.X; //Flip the sign of either the X or Y (edit by adam.wulf)
    

    Normalize that perpendicular

    Length = sqrt(P.X * P.X + P.Y * P.Y); //Thats length of perpendicular
    N.X = P.X / Length;
    N.Y = P.Y / Length; //Now N is normalized perpendicular
    

    Calculate 4 points that form a rectangle by adding normalized perpendicular and multiplying it by half of the desired width

    R1.X := Point1.X + N.X * Width / 2;
    R1.Y := Point1.Y + N.Y * Width / 2;
    R2.X := Point1.X - N.X * Width / 2;
    R2.Y := Point1.Y - N.Y * Width / 2;
    R3.X := Point2.X + N.X * Width / 2;
    R3.Y := Point2.Y + N.Y * Width / 2;
    R4.X := Point2.X - N.X * Width / 2;
    R4.Y := Point2.Y - N.Y * Width / 2;
    

    Draw rectangle using these 4 points.

    Here's the picture:

    Drawing rectangle between two points

    EDIT: To answer the comments: If X and Y are the same then the line is exactly diagonal and perpendicular to a diagonal is a diagonal. Normalization is a method of making a length to equal to 1, so that the width of your line in this example will not depend on perpendiculars length (which is equal to lines length here).

提交回复
热议问题