如何在不损失Java比例的情况下使图像在屏幕上覆盖尽可能多的空间?

时间:2018-08-29 14:34:32

标签: java image canvas

我有一张想要在不损失比例的情况下尽可能放大的图像。我也希望它能在不同的屏幕尺寸下工作。我正在使用以下不保留比例的代码:

Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
double screen_width = screenSize.getWidth();
double screen_height = screenSize.getHeight();

Image img = ImageIO.read(<PATH_TO_IMAGE>);
img = img.getScaledInstance((int)screen_width, (int)screen_height, Image.SCALE_SMOOTH);

是否可以在保留比例的同时调整图像大小并在屏幕上占用尽可能多的空间。

2 个答案:

答案 0 :(得分:1)

您有两种选择:保持整个图像可见,但可能会留出很多空间,或者覆盖整个屏幕,但可能会使某些图像过大,因此不可见。

在两种情况下,为了保持比例,您都需要使用一个单一因素进行缩放。

情况a)

BufferedImage img=ImageIO.read(new File(....));
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
double screen_width = screenSize.getWidth();
double screen_height = screenSize.getHeight();
double scalex=screen_width/img.getWidth(), scaley=screen_height/img.getHeight();
double scale=Math.min(scalex, scaley);
int w=(int)(scale*img.getWidth()), h=(int)(scale*img.getHeight());
BufferedImage img2=new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
img2.getGraphics().drawImage(img, 0, 0, w, h, null);

情况b)

BufferedImage img=ImageIO.read(new File(....));
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
double screen_width = screenSize.getWidth();
double screen_height = screenSize.getHeight();
double scalex=screen_width/img.getWidth(), scaley=screen_height/img.getHeight();
double scale=Math.max(scalex, scaley);
int w=(int)(scale*img.getWidth()), h=(int)(scale*img.getHeight());
BufferedImage img2=new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
img2.getGraphics().drawImage(img, 0, 0, w, h, null);

答案 1 :(得分:0)

假设您正在使用Swing,则可以使用Stretch Icon。使用StretchIcon,您可以将其配置为:

  1. 填满整个可用空间,或
  2. 尽可能保持图像比例和缩放比例。

所以您会:

  1. 用您的图片创建StretchIcon
  2. Icon添加到JLabel
  3. 将标签添加到BorderLayout.CENTER的{​​{1}}

现在,当调整框架大小时,图标会自动调整大小。