How to calculate rotation angle from rectangle points?

后端 未结 3 1901
春和景丽
春和景丽 2020-12-03 01:04

I have 4 points 1,2,3,4 that closes a rectangle.

The points are in a array in this following way: x1

3条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-03 02:08

    The center of the rectangle is right between two opposite corners:

    cx = (x1 + x3) / 2
    cy = (y1 + y3) / 2
    

    The size of the rectangle is the distance between two points:

    w = sqrt(pow(x2-x1, 2) + pow(y2-y1, 2))
    h = sqrt(pow(x3-x2, 2) + pow(y3-y2, 2))
    

    The corners of the gray rectangle can be calculated from the center and the size, for example the top left corner:

    x = cx - w / 2
    y = cy - h / 2
    

    The angle is the arctangent of a side of the square:

    a = arctan2(y4 - y1, x4 - x1)
    

    (I'm not sure exactly which angle it returns, or what angle you expect for that matter, so you get to test a bit.)

提交回复
热议问题