代码之家  ›  专栏  ›  技术社区  ›  ʞɔıu

以一定角度画一个方框

  •  0
  • ʞɔıu  · 技术社区  · 6 年前

    如何更改下面的代码,以便DrawRect也接受 angle 参数?

    (x, y) 表示质心。我想我明白了,我想确定四个角的坐标,然后把它们旋转 (x,y) 保持同样的距离。

    # draw a line from a to b
    def line(a, b):
      # [code omitted]
    
    def drawRect(x, y, w, h):
        a = (x - w / 2, y - h / 2)
        b = (x + w / 2, y - h / 2)
        c = (x + w / 2, y + h / 2)
        d = (x - w / 2, y + h / 2)
        line(a, b)
        line(b, c)
        line(c, d)
        line(d, a)
    
    3 回复  |  直到 6 年前
        1
  •  1
  •   John Anderson    6 年前

    另一种可能的解决方案(也未经测试):

    from math import cos, sin, pi
    def drawRect(x, y, w, h, angle):
        x_vec = (cos(angle), sin(angle))
        y_vec = (cos(angle+pi/2.0), sin(angle+pi/2.0))
        a = (x - x_vec[0]*w/2 - y_vec[0]*h/2, y - x_vec[1]*w/2 - y_vec[1]*h/2)
        b = (x + x_vec[0]*w/2 + y_vec[0]*h/2, y - x_vec[1]*w/2 - y_vec[1]*h/2)
        c = (x + x_vec[0]*w/2 + y_vec[0]*h/2, y + x_vec[1]*w/2 + y_vec[1]*h/2)
        d = (x - x_vec[0]*w/2 - y_vec[0]*h/2, y + x_vec[1]*w/2 + y_vec[1]*h/2)
        line(a, b)
        line(b, c)
        line(c, d)
        line(d, a)
    
        2
  •  0
  •   ʞɔıu    6 年前

    你得把这个问题解决掉。绘制矩形和旋转矩形的点可以是单独的函数。通过将旋转转换为类,可以避免多余的计算。

    class rotate:
        def __init__(self, degrees):
            angle = math.radians(degrees)
            self.sin = math.sin(angle)
            self.cos = math.cos(angle)
    
        def pt(self, x, y):
            return x * self.cos + y * self.sin, y * self.cos - x * self.sin
    
    def drawRect(x, y, w, h, degrees):
        rot = rotate(degrees)
        x1, y1 = rot.pt(-w / 2, -h / 2)
        a = x + x1, y + y1
        x2, y2 = rot.pt( w / 2, -h / 2)
        b = x + x2, y + y2
        x3, y3 = rot.pt( w / 2,  h / 2)
        c = x + x3, y + y3
        x4, y4 = rot.pt(-w / 2,  h / 2)
        d = x + x4, y + y4
        line(a, b)
        line(b, c)
        line(c, d)
        line(d, a)
    
        3
  •  0
  •   SpghttCd    6 年前

    我会用 numpy ,因为它允许更方便的数组-在本例中是矩阵计算。

    import numpy as np
    

    首先,您可以定义一个旋转函数,该函数接受度数中的角度并返回相应的旋转矩阵:

    def rot(phi):
      phi = np.deg2rad(phi)
      return np.array([[np.cos(phi), -np.sin(phi)], [np.sin(phi), np.cos(phi)]])
    

    然后可以将旋转添加到函数中,如下所示:

    def drawRect(x, y, w, h, angle):
        a = np.array((-w / 2, -h / 2))
        b = np.array((w / 2, -h / 2))
        c = np.array((w / 2, h / 2))
        d = np.array((-w / 2, h / 2))
        if angle != 0:
            a = np.matmul(rot(angle), a)
            b = np.matmul(rot(angle), b)
            c = np.matmul(rot(angle), c)
            d = np.matmul(rot(angle), d)
        a += [x, y]
        b += [x, y]
        c += [x, y]
        d += [x, y]
        line(a, b)
        line(b, c)
        line(c, d)
        line(d, a)