如何根据给定的度数旋转线

如何根据给定的度数旋转线

本文介绍了如何根据给定的度数旋转线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一条用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));
}

这篇关于如何根据给定的度数旋转线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 11:48