如何在不裁剪的情况下旋转缓冲图像? 有没有办法旋转JLayeredPane或JLabel?

我搜索过它,但我没有得到直接的回答。 我想要一个缓冲的图像被旋转但没有裁剪我知道新的尺寸将是这样的事情

int w = originalImage.getWidth(); int h = originalImage.getHeight(); double toRad = Math.toRadians(degree); int hPrime = (int) (w * Math.abs(Math.sin(toRad)) + h * Math.abs(Math.cos(toRad))); int wPrime = (int) (h * Math.abs(Math.sin(toRad)) + w * Math.abs(Math.cos(toRad))); 

为我提供一种方法。

BTW有没有办法用ImageIcon旋转JLabel

意图:添加到面板和分层窗格,并将其保存到文件(保存分层窗格)。

或者我们可以旋转分层窗格吗?

如何在不裁剪的情况下旋转缓冲图像?

通过计算旋转的BufferedImage的大小,您已经完成了一半的工作。 另一半实际上是创建旋转的BufferedImage 。 您可以通过使用Graphics2D并在将原始图像绘制到新图像之前应用一些坐标转换来实现。 此外,用一些背景颜色绘制“多余”区域是有意义的。

 public BufferedImage rotateImage(BufferedImage originalImage, double degree) { int w = originalImage.getWidth(); int h = originalImage.getHeight(); double toRad = Math.toRadians(degree); int hPrime = (int) (w * Math.abs(Math.sin(toRad)) + h * Math.abs(Math.cos(toRad))); int wPrime = (int) (h * Math.abs(Math.sin(toRad)) + w * Math.abs(Math.cos(toRad))); BufferedImage rotatedImage = new BufferedImage(wPrime, hPrime, BufferedImage.TYPE_INT_RGB); Graphics2D g = rotatedImage.createGraphics(); g.setColor(Color.LIGHT_GRAY); g.fillRect(0, 0, wPrime, hPrime); // fill entire area g.translate(wPrime/2, hPrime/2); g.rotate(toRad); g.translate(-w/2, -h/2); g.drawImage(originalImage, 0, 0, null); g.dispose(); // release used resources before g is garbage-collected return rotatedImage; } 

以下是上述代码中的测试示例:

原始图像
原版的

旋转图像(30度)
旋转

BTW有没有办法用ImageIcon旋转JLabel?

更简单的方法是旋转图标,而不是标签。

查看旋转图标以查找旋转的类,并在旋转时重新计算图标的大小。

意图:添加到面板和分层窗格,并将其保存到文件(保存分层窗格)。

不确切地知道这意味着什么,但如果您只想保存分层窗格的“图像”,请查看屏幕图像 。