7

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

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

4

2 回答 2

26

如果您使用的是 plain GraphicsGraphics2D请先转换为:

Graphics2D g2d = (Graphics2D)g;

旋转整个Graphics2D

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

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

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

例子:

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
    }
}
于 2013-01-02T15:32:38.220 回答
3

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

于 2013-01-02T15:32:34.610 回答