如何使用Java/Swing旋转图像,然后将其原点设置为0,0? [英] How can I rotate an image using Java/Swing and then set its origin to 0,0?

查看:160
本文介绍了如何使用Java/Swing旋转图像,然后将其原点设置为0,0?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我能够旋转已添加到JLabel的图像.唯一的问题是,如果高度和宽度不相等,则旋转的图像将不再出现在JLabel的原点(0,0).

I'm able to rotate an image that has been added to a JLabel. The only problem is that if the height and width are not equal, the rotated image will no longer appear at the JLabel's origin (0,0).

这就是我在做什么.我还尝试过使用AffineTransform并旋转图像本身,但结果相同.

Here's what I'm doing. I've also tried using AffineTransform and rotating the image itself, but with the same results.

Graphics2D g2d = (Graphics2D)g;
g2d.rotate(Math.toRadians(90), image.getWidth()/2, image.getHeight()/2);
super.paintComponent(g2d);

如果我的图像的宽度大于其高度,则使用此方法旋转该图像然后进行绘画,将导致该图像在点0,0上方垂直绘制,并在点0右侧水平绘制,0.

If I have an image whose width is greater than its height, rotating that image using this method and then painting it will result in the image being painted vertically above the point 0,0, and horizontally to the right of the point 0,0.

推荐答案

使用g2d.transform()将图像移回需要的位置.我只是在想计算可能是什么,但我想是这样的:

Use the g2d.transform() to shift the image back where it's needed. I'm just imagining what the calculation might be but I think something like:

int diff = ( image.getWidth() - image.getHeight() ) / 2;
g2.transform( -diff, diff );

顺便说一句,标签可能会报告其首选大小-您可能需要覆盖getPreferredSize()并考虑旋转后交换图像的宽度和高度.

BTW, you may have a problem with the label reporting its preferred size - you might need to override getPreferredSize() and account for swapping the images width and height if rotated.

这篇关于如何使用Java/Swing旋转图像,然后将其原点设置为0,0?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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