如何在Java中旋转图形 [英] How to rotate Graphics in Java

查看:274
本文介绍了如何在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 first:

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

Graphics2D g2d = (Graphics2D)g;

旋转整个 Graphics2D



To rotate an entire 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆