如何根据给定的度数

时间:2015-04-26 18:35:29

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

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

谢谢!

4 个答案:

答案 0 :(得分:3)

您可以为原始行创建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));
}

答案 1 :(得分:1)

好吧,你需要计算线的长度,假设线的末端是(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);

答案 2 :(得分:0)

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

答案 3 :(得分:0)

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);
}