这已经困扰我一段时间了,但我似乎无法弄清楚我做错了什么。所以我用图像图标设置面板的背景,但是当我调整窗口大小时,它使 BG 保持相同的大小,并且我在暴露的边缘周围得到了这个巨大的白墙,我想将 bg 拉伸(stretch)为窗口变化
这是我的相关代码
protected JPanel createRightPane() {
final ImageIcon BGiconSM = ScaledImageIcon("parchmentTall.jpg", "BG Plate", initalWidth/2, initalHeight);
final ImageIcon iconSM = ScaledImageIcon("titlebar.png", "Title Bar BG", (initalWidth/3), 40);
//TODO Parchment image resize
final JPanel content = new JPanel(new GridBagLayout());
content.setOpaque(false);
final JPanel panel = new JPanel(new BorderLayout()) {
protected void paintComponent(Graphics g)
{
// Dispaly image at full size
Image BGicon = BGiconSM.getImage();
g.drawImage(BGicon, 0, 0, null);
super.paintComponent(g);
}
};
panel.addComponentListener(new ComponentAdapter() {
@Override
public void componentResized(ComponentEvent e){
Rectangle r = frame.getBounds();
int h = r.height;
int w = r.width;
if (h >= initalHeight){h = initalHeight-30;}
//System.out.println(h);
//System.out.println(w);
/* protected paintComponent(Graphics g)
{
// Dispaly image at full size
Image BGicon = BGiconSM.getImage();
g.drawImage(BGicon, 0, 0, null);
super.paintComponent(g);
}
*/
}
});
最佳答案
问题是,为什么要(调整大小)?您只告诉 Graphics
上下文它应该在组件的左上角 (0x0) 绘制图像。
您应该看看Graphics#drawImage(Image, int, int, int, int, ImageObserver)
和 Graphics2D#drawImage(Image, AffineTransform, ImageObserver)
您还应该看看:
- Java: maintaining aspect ratio of JPanel background image
- Quality of Image after resize very low -- Java
- The Perils of Image.getScaledInstance()
有关缩放图像的不同方法的讨论
您还破坏了油漆链,这导致了“白墙”。在执行任何自定义绘画之前,您应该调用 super.paintComponent
。
当为了自定义绘制而重写诸如 JPanel
或 JComponent
之类的容器时,您还应该考虑重写 getPreferredSize
方法,这将为布局管理器提供将组件调整为适当的默认大小的方法,而不是使用通常为默认大小的 0x0
。
关于java - 调整窗口上的 ImageIcon 大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25967481/