问题描述
我正在尝试旋转 BufferedImage
并将其显示在 JLabel
中(在<$ c内) $ C>的JPanel )。当前结果产生一个相对于黑色背景旋转10度的白色正方形,但图像不在正方形内。我知道 myPicture
不是空白的,因为 myPicture
本身在 JPanel $中正确显示c $ c>不旋转时。
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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!