如何在Java中旋转图形
我在如何在Java中旋转图形,java,graphics,rotation,Java,Graphics,Rotation,我在JPanel中绘制了一些图形,如圆形、矩形等 但是我想画一些旋转了一定角度的图形,比如旋转的椭圆。我该怎么办?在您的paintComponent()重写方法中,将Graphics参数强制转换为Graphics2D,调用此Graphics2D,然后绘制椭圆。如果您使用的是普通图形,请先强制转换为Graphics2D: Graphics2D g2d = (Graphics2D)g; 要旋转整个图形2d: g2d.rotate(Math.toRadians(degrees)); //draw s
JPanel
中绘制了一些图形,如圆形、矩形等
但是我想画一些旋转了一定角度的图形,比如旋转的椭圆。我该怎么办?在您的
paintComponent()
重写方法中,将Graphics参数强制转换为Graphics2D,调用此Graphics2D,然后绘制椭圆。如果您使用的是普通图形
,请先强制转换为Graphics2D
:
Graphics2D g2d = (Graphics2D)g;
要旋转整个图形2d
:
g2d.rotate(Math.toRadians(degrees));
//draw shape/image (will 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
}
}
非常感谢您,以及如何从旧仿射变换转换新位置?@KidLet这可能会有所帮助:您可以使用
旋转
,缩放
,以及翻译
。
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
}
}