问题描述
我正在尝试旋转 BufferedImage
并将其显示在 JLabel
(位于 JPanel
内)内.当前结果生成一个在黑色背景上旋转 10 度的白色方块,但图像不存在于方块内.我知道 myPicture
不是空白的,因为 myPicture
本身在不旋转时会在 JPanel
内正确显示.
I am trying to rotate a BufferedImage
and display it inside a JLabel
(which is inside a JPanel
). The current result produces a white square rotated 10 degrees against a black background, but the image is not present inside the square. I know myPicture
is not blank, since myPicture
itself displays properly inside the JPanel
when not rotated.
代码如下:
int w = myPicture.getWidth();
int h = myPicture.getHeight();
BufferedImage newImage = new BufferedImage(w, h, myPicture.getType());
Graphics2D graphic = newImage.createGraphics();
graphic.rotate(Math.toRadians(10), w/2, h/2);
graphic.drawImage(myPicture, null, 0, 0);
picLabel.setIcon(new ImageIcon(newImage));
推荐答案
我自己解决了问题.问题出在代码上:
I solved my own issue. The problem lay in the code:
myPicture.getType()
由于您可以放入程序的图像类型有很多可变性,当您开始绘制新的 BufferedImage 时,结果将是不可预测的.我通过显式设置类型解决了这个问题,在我的情况下需要
Since there is a lot of variability in the types of images you could put in to the program, the results are going to be unpredictable when you start drawing into the new BufferedImage. I solved the problem by setting the type explicitly, which in my case required
BufferedImage.TYPE_INT_ARGB
所以完整的声明如下:
BufferedImage newImage = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
这篇关于在 JPanel 内旋转 BufferedImage的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!