[英]Create a square polygon (random oriented) from midpoints in Python
我有一個中點(x,y),我需要使用2D(隨機)平面旋轉來創建具有隨機方向的正方形多邊形。
def get_square_plot(x, y, side):
return [(x-(side/2), y+(side/2)), (x+(side/2), y+(side/2)), (x+(side/2), y-(side/2)), (x-(side/2), y-(side/2))]
此函數創建沒有特定方向的正方形多邊形的頂點。 我希望改進此功能,以增加隨機旋轉這些頂點的可能性(如果可能,並具有特定角度)
如果我對您的理解正確,那么它應該可以執行您想要的操作:
from math import sin, cos, radians
def rotated_square(cx, cy, size, degrees=0):
""" Calculate coordinates of a rotated square centered at 'cx, cy'
given its 'size' and rotation by 'degrees' about its center.
"""
h = size/2
l, r, b, t = cx-h, cx+h, cy-h, cy+h
a = radians(degrees)
cosa, sina = cos(a), sin(a)
pts = [(l, b), (l, t), (r, t), (r, b)]
return [(( (x-cx)*cosa + (y-cy)*sina) + cx,
(-(x-cx)*sina + (y-cy)*cosa) + cy) for x, y in pts]
print rotated_square(50, 50, 100)
輸出:
[(0.0, 0.0), (0.0, 100.0), (100.0, 100.0), (100.0, 0.0)]
請注意,在一般情況下,結果坐標不會是整數。
這樣做的有效作用是,首先通過從坐標中減去cx,cy來將每個坐標轉換為原點,然后將其旋轉角度,然后將其取消平移相同的量。 這對於補償旋轉公式通常相對於坐標系原點的事實是必要的。
確定了四個角坐標后,您可以使用簡單的2D矩陣旋轉將它們相對於原點(或中點)旋轉:
http://en.wikipedia.org/wiki/Rotation_%28mathematics%29 (搜索2D旋轉方程式)
x' = x cos(theta) - y sin(theta)
y' = x sin(theta) + y cos(theta)
您可以將內置的Python Math庫用於cos / sin函數: http : //docs.python.org/2/library/math.html第9.2.3節
Math.cos(theta)
Math.sin(theta)
我希望這是有用的!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.