pro*_*irl 1 java graphics user-interface awt computational-geometry
我用 Graphics 对象绘制了一条线。我想根据鼠标拖动的程度将这条线旋转一定的角度。我可以获得旋转它所需的度数,但是我如何根据该角度旋转线呢?
谢谢你!
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));
}
Run Code Online (Sandbox Code Playgroud)