如何在Java中旋转图形

时间:2022-04-15 11:05:01

I have drawn some Graphics in a JPanel, like circles, rectangles, etc.

我在JPanel中绘制了一些图形,如圆形,矩形等。

But I want to draw some Graphics rotated a specific degree amount, like a rotated ellipse. What should I do?

但我想绘制一些特定程度旋转的图形,如旋转的椭圆。我该怎么办?

2 个解决方案

#1


19  

If you are using plain Graphics, cast to Graphics2D first:

如果您使用的是普通图形,请首先转换为Graphics2D:

Graphics2D g2d = (Graphics2D)g;

To rotate an entire Graphics2D:

要旋转整个Graphics2D:

g2d.rotate(Math.toRadians(degrees));
//draw shape/image (will be rotated)

To reset the rotation (so you only rotate one thing):

要重置旋转(所以你只旋转一件事):

AffineTransform old = g2d.getTransform();
g2d.rotate(Math.toRadians(degrees));
//draw shape/image (will be rotated)
g2d.setTransform(old);
//things you draw after here will not be rotated

Example:

例:

class MyPanel extends JPanel {
    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D)g;
        AffineTransform old = g2d.getTransform();
        g2d.rotate(Math.toRadians(degrees));
        //draw shape/image (will be rotated)
        g2d.setTransform(old);
        //things you draw after here will not be rotated
    }
}

#2


3  

In your paintComponent() overridden method, cast the Graphics argument to Graphics2D, call rotate() on this Graphics2D, and draw your ellipse.

在paintComponent()重写方法中,将Graphics参数强制转换为Graphics2D,在此Graphics2D上调用rotate(),然后绘制椭圆。

#1


19  

If you are using plain Graphics, cast to Graphics2D first:

如果您使用的是普通图形,请首先转换为Graphics2D:

Graphics2D g2d = (Graphics2D)g;

To rotate an entire Graphics2D:

要旋转整个Graphics2D:

g2d.rotate(Math.toRadians(degrees));
//draw shape/image (will be rotated)

To reset the rotation (so you only rotate one thing):

要重置旋转(所以你只旋转一件事):

AffineTransform old = g2d.getTransform();
g2d.rotate(Math.toRadians(degrees));
//draw shape/image (will be rotated)
g2d.setTransform(old);
//things you draw after here will not be rotated

Example:

例:

class MyPanel extends JPanel {
    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D)g;
        AffineTransform old = g2d.getTransform();
        g2d.rotate(Math.toRadians(degrees));
        //draw shape/image (will be rotated)
        g2d.setTransform(old);
        //things you draw after here will not be rotated
    }
}

#2


3  

In your paintComponent() overridden method, cast the Graphics argument to Graphics2D, call rotate() on this Graphics2D, and draw your ellipse.

在paintComponent()重写方法中,将Graphics参数强制转换为Graphics2D,在此Graphics2D上调用rotate(),然后绘制椭圆。