我正在使用根据xy坐标及其宽度和高度定义的矩形.我想出了如何用坐标(x = cos(deg) * x - sin(deg) * y y = sin(deg) * x + cos(deg) * y)来旋转它们但是我被卡在高度和宽度上.我确信有一个明显的解决方案我不知道.如果重要,我正在使用Python.
编辑抱歉这个令人困惑的描述.我的目的是通过任何角度来使宽度和高度反转或取消.例如,在90度旋转中,值将切换.在180度旋转中,宽度将为负.另外,我只打算在我的脚本中使用90的倍数.我可以只使用if语句,但我认为会有更"优雅"的方法.
只需计算矩形的四个角:
p1 = (x, y)
p2 = (x + w, y)
p3 = (x, y + h)
Run Code Online (Sandbox Code Playgroud)
并按角度旋转你想要:
p1 = rotate(p1, angle)
# and so on...
Run Code Online (Sandbox Code Playgroud)
并转换回您的矩形表示:
x, y = p1
w = dist(p1, p2) # the same as before rotation
h = dist(p1, p3)
Run Code Online (Sandbox Code Playgroud)
其中dist计算两点之间的距离.
编辑:你为什么不尝试申请公式你写的(width, height)配对?
x1 = cos(deg) * x - sin(deg) * y
y2 = sin(deg) * x + cos(deg) * y
Run Code Online (Sandbox Code Playgroud)
很容易看出,如果deg == 90值将切换:
x1 = -y
y2 = x
Run Code Online (Sandbox Code Playgroud)
如果deg == 180他们被否定:
x1 = -x
y2 = -y
Run Code Online (Sandbox Code Playgroud)
等等......我认为这就是你要找的东西.
EDIT2:
这里有快速旋转功能:
def rotate_left_by_90(times, x, y):
return [(x, y), (-y, x), (-x, -y), (y, -x)][times % 4]
Run Code Online (Sandbox Code Playgroud)
从您描述的仅旋转 90 度的方式以及您似乎定义宽度和高度的方式来看,也许您正在寻找类似的东西
direction = 1 // counter-clockwise degrees
// or
direction = -1 // clockwise 90 degrees
new_height = width * direction
new_width = -height * direction
width = new_width
height = new_height
Run Code Online (Sandbox Code Playgroud)
不知道为什么你想要宽度和高度为负值,因为否则每次 90 度旋转实际上只是交换宽度和高度,无论你以哪种方式旋转。