如何在 Java 中旋转图形 [英] How to rotate Graphics in Java
本文介绍了如何在 Java 中旋转图形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在 JPanel
中绘制了一些图形,例如圆形、矩形等.
I have drawn some Graphics in a JPanel
, like circles, rectangles, etc.
但我想绘制一些旋转特定度数的图形,如旋转椭圆.我该怎么办?
But I want to draw some Graphics rotated a specific degree amount, like a rotated ellipse. What should I do?
推荐答案
如果你使用的是普通的 Graphics
,请先转换为 Graphics2D
:
If you are using plain Graphics
, cast to Graphics2D
first:
Graphics2D g2d = (Graphics2D)g;
要旋转整个 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
示例:
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
}
}
这篇关于如何在 Java 中旋转图形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文