Drawing rectangle between two points with arbitrary width

后端 未结 3 1765
被撕碎了的回忆
被撕碎了的回忆 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:44

    Easy way (I'll call the "width" the thickness of the line):

    We need to calculate 2 values, the shift on the x axis and the shift on the y axis for each of the 4 corners. Which is easy enough.

    The dimensions of the line are:

    width = x2 - x1
    
    height = y2 - y1
    

    Now the x shift (let's call it xS):

    xS = (thickness * height / length of line) / 2
    
    yS = (thickness * width / length of line) / 2
    

    To find the length of the line, use Pythagoras's theorem:

    length = square_root(width * width + height * height)
    

    Now you have the x shift and y shift.

    First coordinate is: (x1 - xS, y1 + yS)
    
    Second: (x1 + xS, y1 - yS)
    
    Third: (x2 + xS, y2 - yS)
    
    Fourth: (x2 - xS, y2 + yS)
    

    And there you go! (Those coordinates are drawn counterclockwise, the default for OpenGL)

提交回复
热议问题