如何根据给定的度数旋转线 [英] How to rotate a line based on a given number of degrees
本文介绍了如何根据给定的度数旋转线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一条用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?
谢谢!
推荐答案
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));
}
这篇关于如何根据给定的度数旋转线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文