您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

在给定两个顶点的情况下围绕中心点旋转线

在给定两个顶点的情况下围绕中心点旋转线

点(x1,y1)和(x2,y2)之间的线段的中心点(cx,cy)的坐标为:

    cx = (x1 + x2) / 2
    cy = (y1 + y2) / 2

换句话说,它只是两对x和y坐标值的平均值或算术平均值。

对于多段线或折线,其逻辑中心点的x和y坐标只是所有点的x和y值的相应平均值。平均值就是值的总和除以它们的数量

绕原点 (0,0)旋转2D点(x,y)θ弧度的一般公式为: __

    x′ = x * cos(θ) - y * sin(θ)
    y′ = x * sin(θ) + y * cos(θ)

为了绕不同的中心(cx,cy)进行旋转,需要通过先从该点的坐标中减去所需旋转中心的坐标来调整该点的x和y值,这具有移动效果(已知在几何学上是平移),其数学表达如下:

    tx = x - cx
    ty = y - cy

然后将此中间点旋转所需的角度,最后将旋转点的x和y值加 回到 每个坐标的x和y上。用几何术语来说,它是以下操作序列:T???s????─?R?????─?U?????s????。

通过仅将描述的数学应用于其中的每个线段的每个点,可以扩展该概念以允许围绕任意点(例如其自己的逻辑中心)旋转整条折线。

为了简化此计算的实现,可以将所有三组计算的数值结果组合在一起,并用一对同时执行它们的数学公式来表示。因此,通过使用以下点旋转一个现有点(x,y),围绕该点(cx,cy)的θ弧度可以获得新点(x’,y’):

    x′ = (  (x - cx) * cos(θ) + (y - cy) * sin(θ) ) + cx
    y′ = ( -(x - cx) * sin(θ) + (y - cy) * cos(θ) ) + cy

将此数学/几何概念整合到您的函数中会产生以下结果:

from math import sin, cos, radians

def rotate_lines(self, deg=-90):
    """ Rotate self.polylines the given angle about their centers. """
    theta = radians(deg)  # Convert angle from degrees to radians
    cosang, sinang = cos(theta), sin(theta)

    for pl in self.polylines:
        # Find logical center (avg x and avg y) of entire polyline
        n = len(pl.lines)*2  # Total number of points in polyline
        cx = sum(sum(line.get_xdata()) for line in pl.lines) / n
        cy = sum(sum(line.get_ydata()) for line in pl.lines) / n

        for line in pl.lines:
            # Retrieve vertices of the line
            x1, x2 = line.get_xdata()
            y1, y2 = line.get_ydata()

            # Rotate each around whole polyline's center point
            tx1, ty1 = x1-cx, y1-cy
            p1x = ( tx1*cosang + ty1*sinang) + cx
            p1y = (-tx1*sinang + ty1*cosang) + cy
            tx2, ty2 = x2-cx, y2-cy
            p2x = ( tx2*cosang + ty2*sinang) + cx
            p2y = (-tx2*sinang + ty2*cosang) + cy

            # Replace vertices with updated values
            pl.set_line(line, [p1x, p2x], [p1y, p2y])
其他 2022/1/1 18:42:08 有535人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶