Java 调整imaget的大小以缩小其所在的面板/标签
我已经能够使字体与组件的大小成比例,但是,我似乎不知道如何使图像比例。我的程序的工作方式是将组件添加到arrayList,然后在最后设置每个组件的边界。我尝试了这一版本,但无法使其正常工作:Java 调整imaget的大小以缩小其所在的面板/标签,java,image,swing,graphics2d,Java,Image,Swing,Graphics2d,我已经能够使字体与组件的大小成比例,但是,我似乎不知道如何使图像比例。我的程序的工作方式是将组件添加到arrayList,然后在最后设置每个组件的边界。我尝试了这一版本,但无法使其正常工作: public class ImagePanel extends JPanel implements Updater{ BufferedImage resizer; private int width; private int height; private JLabel pi
public class ImagePanel extends JPanel implements Updater{
BufferedImage resizer;
private int width;
private int height;
private JLabel picLabel;
private BufferedImage myPicture;
/**
* Searches for the image in the specified location and sets the background of the ImagePanel to the specified color.
* @param location
* @param bGColor
*/
public ImagePanel(String location, Color bGColor)
{
myPicture = null;
this.setLayout(new BorderLayout());
try {
// TODO make it use the string.
myPicture = ImageIO.read(new File("images/logo-actavis.png"));
} catch (IOException e) {
e.printStackTrace();
}
picLabel = new JLabel(new ImageIcon(myPicture));
add(picLabel,BorderLayout.CENTER);
this.addComponentListener(new ComponentAdapter() {
@Override
/**
* Makes it so it does not stretch out text. Resizes the fonts to scale with the screen width..
*/
public void componentResized(ComponentEvent e) {
if(picLabel.getHeight()!=0&&picLabel.getWidth()!=0)
{
width = picLabel.getWidth();
height = picLabel.getHeight();
myPicture=resize(myPicture, width, height);
}
}
});
this.setBackground(bGColor);
}
public static BufferedImage resize(BufferedImage image, int width, int height) {
BufferedImage bi = new BufferedImage(width, height, BufferedImage.TRANSLUCENT);
Graphics2D g2d = (Graphics2D) bi.createGraphics();
g2d.addRenderingHints(new RenderingHints(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY));
g2d.drawImage(image, 0, 0, width, height, null);
g2d.dispose();
return bi;
}
}
您可以使用该方法从原始图像获取缩放图像
public Image getScaledInstance(int-width、int-height、int-hints)
而不是使用图像图标。你可以用Darryl的
图标将根据标签的可用空间自动缩放。您可以按比例缩放图像,也可以让图像填充整个空间。最后这样做:
this.addComponentListener(new ComponentAdapter() {
@Override
/**
* Makes it so it does not stretch out text. Resizes the fonts to scale with the screen width..
*/
public void componentResized(ComponentEvent e) {
Double width = (double) e.getComponent().getWidth();
Double height = (double) e.getComponent().getHeight();
double scalingFactor=Math.min(width/originalWidth, height/originalHeight)*.7;
myPicture = myPicture.getScaledInstance((int)(originalWidth*(scalingFactor)),(int) (originalHeight*(scalingFactor)), Image.SCALE_SMOOTH);
picLabel = new JLabel(new ImageIcon(myPicture));
add(picLabel,BorderLayout.CENTER);
}
});
其中,原始高度/宽度是原始图片的纵横比。我将scalingFactor乘以.7,因为我不希望它填满整个面板