在Python中从中点创建一个随机方向的正方形多边形

0 投票
2 回答
803 浏览
提问于 2025-04-17 22:01

我有一个中点(x,y),我需要用这个点创建一个方形的多边形,并且这个方形可以随机旋转。

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))]

这个函数可以生成一个没有特定方向的方形多边形的顶点。我想改进这个函数,让它可以随机旋转这些顶点(如果可以的话,也希望能指定一个特定的角度)。

2 个回答

0

确定了四个角的坐标后,你可以通过一个简单的二维矩阵旋转,把它们相对于原点(或者说中点)进行旋转:

http://en.wikipedia.org/wiki/Rotation_%28mathematics%29 (可以搜索二维旋转公式)

x' = x cos(theta) - y sin(theta)
y' = x sin(theta) + y cos(theta)

你可以使用Python自带的数学库来计算余弦和正弦函数:http://docs.python.org/2/library/math.html 第9.2.3节

Math.cos(theta)
Math.sin(theta)

希望这些对你有帮助!

1

如果我理解得没错,这段代码应该能实现你想要的效果:

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 将每个坐标移动到原点,然后根据给定的角度进行旋转,最后再将坐标移回去。这样做是为了弥补旋转公式通常是相对于坐标系的原点来计算的这个事实。

撰写回答