旋转 BufferedImage 实例 [英] Rotating BufferedImage instances

查看:57
本文介绍了旋转 BufferedImage 实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法显示旋转的 BufferedImage.我认为旋转工作得很好,但我实际上无法将其绘制到屏幕上.我的代码:

I am having trouble getting a rotated BufferedImage to display. I think the rotation is working just fine, but I can't actually draw it to the screen. My code:

Class extends JPanel {
    BufferedImage img;
    int rotation = 0;

    public void paintComponent(Graphics g) {
        g.clearRect(0, 0, getWidth(), getHeight());
        img2d = img.createGraphics();
        img2d.rotate(Math.toRadians(rotation), img.getWidth() / 2, img.getHeight() / 2);
        g.drawImage(img, imgx, imgy, null);
        this.repaint();
    }
}

这对我不起作用.我找不到任何方法将旋转的 img2d 绘制到 g 上.

This is not working for me. I could not find any way to draw the rotated img2d onto g.

我有多个对象被绘制到 g 上,所以我无法旋转它.我需要能够单独旋转事物.

I have multiple objects that are being drawn onto g, so I can't rotate that. I need to be able to rotate things individually.

推荐答案

我会使用 Graphics2D.drawImage(image, affinetranform, imageobserver).

下面的代码示例旋转图像并将其平移到组件的中心.这是结果的截图:

The code example below rotates and translates an image to the center of the component. This is a screenshot of the result:

public static void main(String[] args) throws IOException {
    JFrame frame = new JFrame("Test");

    frame.add(new JComponent() {
        BufferedImage image = ImageIO.read(
                new URL("http://upload.wikimedia.org/wikipedia/en/2/24/Lenna.png"));

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);

            // create the transform, note that the transformations happen
            // in reversed order (so check them backwards)
            AffineTransform at = new AffineTransform();

            // 4. translate it to the center of the component
            at.translate(getWidth() / 2, getHeight() / 2);

            // 3. do the actual rotation
            at.rotate(Math.PI / 4);

            // 2. just a scale because this image is big
            at.scale(0.5, 0.5);

            // 1. translate the object so that you rotate it around the 
            //    center (easier :))
            at.translate(-image.getWidth() / 2, -image.getHeight() / 2);

            // draw the image
            Graphics2D g2d = (Graphics2D) g;
            g2d.drawImage(image, at, null);

            // continue drawing other stuff (non-transformed)
            //...
        }
    });

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(400, 400);
    frame.setVisible(true);
}

这篇关于旋转 BufferedImage 实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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