问题描述
我有一条用Graphics对象绘制的线.我想根据鼠标拖动的多少将此线旋转一定程度.我可以获得旋转所需的度数,但是如何根据该度数旋转线呢?
I have a line drawn with a Graphics object. I want to rotate this line a certain amount of degrees based on how much the mouse is dragged. I can get the number of degrees i need to rotate it but how do i then rotate the line based on that?
谢谢!
推荐答案
您可以创建 Line2D
对象.然后,您可以使用 AffineTransform#getRotateInstance
以获得AffineTransform
,该AffineTransform
围绕特定点绕特定角度旋转.使用此AffineTransform
,可以创建旋转的Line2D
对象进行绘制.因此您的绘画代码大致如下:
You can create a Line2D
object for your original line. Then you can use AffineTransform#getRotateInstance
to obtain an AffineTransform
that does the rotation about a certain angle, around a certain point. Using this AffineTransform
, you can create a rotated Line2D
object to paint. So your painting code could roughly look like this:
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));
}
这篇关于如何根据给定的度数旋转线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!