我有一个全屏JFrame,我想通过在图片中填充JLabel并将其尺寸与屏幕尺寸相匹配来为它创建背景。
虽然我可以创建一个与屏幕尺寸相匹配的JLabel,但我似乎无法调整图像的大小以适应。从本质上讲,我希望最终得到一个完全充满图像的全屏JFrame(无论图像或屏幕的尺寸如何)。
目前的代码如下,谢谢!
public void addBackground(ImageIcon imgIcon) {
Image img = imgIcon.getImage();
BufferedImage buffImg = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB);
BufferedImage resizeBuffImg = resize(buffImg, screenSize.width, screenSize.height);
Image finalImg = Toolkit.getDefaultToolkit().createImage(resizeBuffImg.getSource());
ImageIcon back = new ImageIcon(finalImg);
System.out.println("IMAGE WIDTH: " + back.getIconWidth());
System.out.println("IMAGE HEIGHT: " + back.getIconHeight());
JLabel backgroundLabel = new JLabel(back);
getContentPane().add(backgroundLabel);
}
public BufferedImage resize(BufferedImage image, int width, int height) {
int type = image.getType() == 0? BufferedImage.TYPE_INT_ARGB : image.getType();
BufferedImage resizedImage = new BufferedImage(width, height, type);
Graphics2D g = resizedImage.createGraphics();
g.setComposite(AlphaComposite.Src);
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g.setRenderingHint(RenderingHints.KEY_RENDERING,
RenderingHints.VALUE_RENDER_QUALITY);
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g.drawImage(image, 0, 0, width, height, null);
g.dispose();
return resizedImage;
}
编辑 - 知道了!使用Image的getScaledInstance()可以正常工作。它并不完美,但我打算缩小大图像,而不是扩大较小的图像。