gpt4 book ai didi

java - 调整图像大小以缩小其所在的面板/标签

转载 作者:行者123 更新时间:2023-12-02 04:35:59 26 4
gpt4 key购买 nike

我已经能够使字体随着组件的大小而缩放,但是,我似乎无法弄清楚如何使图像缩放。我的程序的工作方式是将组件添加到 arrayList 中,然后在最后设置每个组件的边界。我尝试了此方法的变体,但无法使其工作:

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 宽度,int 高度,int 提示)

关于java - 调整图像大小以缩小其所在的面板/标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30739008/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com