【问题标题】:How to rotate a line based on a given number of degrees如何根据给定的度数旋转一条线
【发布时间】:2015-07-05 02:00:29
【问题描述】:

我用 Graphics 对象画了一条线。我想根据鼠标拖动的程度将这条线旋转一定的度数。我可以得到我需要旋转它的度数,但是我如何根据它旋转线?

谢谢!

【问题讨论】:

  • 你想围绕它的一端旋转线条吗?
  • 或任意点附近?
  • 这条线是直的(平行于 x 轴),我希望第二个点根据我的角度移动一定量
  • 意思是在它的一端是肯定的

标签: java user-interface graphics awt computational-geometry


【解决方案1】:

您可以为原始行创建一个Line2D 对象。然后您可以使用AffineTransform#getRotateInstance 获得一个AffineTransform,它围绕某个点围绕某个角度进行旋转。使用这个AffineTransform,您可以创建一个旋转的Line2D 对象来绘制。所以你的绘画代码大概是这样的:

protected void paintComponent(Graphics gr) {
    super.paintComponent(gr);
    Graphics2D g = (Graphics2D)gr; 

    // Create the original line, starting at the origin,
    // and extending along the x-axis
    Line2D line = new Line2D.Double(0,0,100,0);

    // Obtain an AffineTransform that describes a rotation
    // about a certain angle (given in radians!), around
    // the start point of the line. (Here, this is the
    // origin, so this could be simplified. But in this
    // form, it's more generic)
    AffineTransform at = 
        AffineTransform.getRotateInstance(
            Math.toRadians(angleInDegrees), line.getX1(), line.getY1());

    // Draw the rotated line
    g.draw(at.createTransformedShape(line));
}

【讨论】:

    【解决方案2】:

    好的,你需要计算线的长度,假设线的末端是(x0,y0)和(x1,y1),而(x,y)是鼠标坐标,你想要什么是在 (x0,y0) 和 (x,y) 之间的线上的点 (x2,y2),(x0,y0) 和 (x2,y2) 之间的距离必须与 (x0, y0) 和 (x1,y1)。

    (x0,y0) 和 (x1,y1) 之间的距离为:

    double dx = x1-x0;
    double dy = y1-y0;
    double length = Math.sqrt(dx*dx, dy*dy);
    

    (x0,y0) 和 (x,y) 之间的距离为:

    double dx1 = x-x0;
    double dy1 = y-y0;
    double mouseDist = Math.sqrt(dx1*dx1, dy1*dy1);
    

    而 (x2,y2) 是:

    int x2 = x0 + (int)(dx1*length/mouseDist);
    int y2 = y0 + (int)(dy1*length/mouseDist);
    

    【讨论】:

      【解决方案3】:

      我想你说的是Java AWT Graphics 类。图形可以被认为是画布。它是一个像素值数组,“画一条线”只是一个改变其中一些像素值的实用函数——从它的角度来看,没有“线对象”可言。通常你应该擦除整个东西并以你想要的角度画一条新线。但是,为此,您可能需要查看 Graphics2D (http://docs.oracle.com/javase/7/docs/api/java/awt/Graphics2D.html),尤其是 setTransform 和 AffineTransform 类。

      【讨论】:

      • 清嗓子docs.oracle.com/javase/8/docs/api/java/awt/geom/Line2D.html。 “擦除”这条线通常不是一个好主意。 AWT/Swing 中的绘制机制建议线条应该已经在其旋转状态下绘制。
      • 是的,这就是我想说的。我的意思是擦除整个画布并重新绘制。
      【解决方案4】:
      static Point rotateLineClockWise(Point center, Point edge, int angle) {
          double xRot = (int) center.x + Math.cos(Math.toRadians(angle)) * (edge.x - center.x) - Math.sin(Math.toRadians(angle)) * (edge.y - center.y);
          double yRot = (int) center.y + Math.sin(Math.toRadians(angle)) * (edge.x - center.x) + Math.cos(Math.toRadians(angle)) * (edge.y - center.y);
          return new Point((int) xRot, (int) yRot);
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-01-28
        • 1970-01-01
        相关资源
        最近更新 更多