Find corners of a rotated rectangle given its center point and rotation

百般思念 提交于 2019-12-24 10:57:34

问题


Can someone give me an algorithm that finds the position of all four corners of a rectangle if I know its center point(in global coordinate space), width and height, and its rotation around that center point?

clarification edit: The width and height I am referring to is the length of the sides of the rectangle.


回答1:


Top right corner has coordinates w/2, h/2 relative to the center. After rotation its absolute coordinates are

 x = cx + w/2 * Cos(Phi) - h/2 * Sin(Phi)
 y = cy + w/2 * Sin(Phi) + h/2 * Cos(Phi)



回答2:


If you need all of the corners, it just might be faster to create two perpendicular vectors from the center of the rectangle to both of its sides, and then to add/subtract these vectors to/from the center of the rectangle to form the points.

This might be faster, since you don't need to repeatedly call sin() and cos() functions (you do so only once for each).

Assuming we have a Vector library (for cleaner code - only helps with vector arithmetic), here is the code in Python:

def get_corners_from_rectangle(center: Vector, angle: float, dimensions: Vector):
   # create the (normalized) perpendicular vectors
   v1 = Vector(cos(angle), sin(angle))
   v2 = Vector(-v1[1], v1[0])  # rotate by 90

   # scale them appropriately by the dimensions
   v1 *= dimensions[0] / 2
   v2 *= dimensions[1] / 2

   # return the corners by moving the center of the rectangle by the vectors
   return [
      center + v1 + v2,
      center - v1 + v2,
      center - v1 - v2,
      center + v1 - v2,
   ]


来源:https://stackoverflow.com/questions/41898990/find-corners-of-a-rotated-rectangle-given-its-center-point-and-rotation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!