我想“最简单”的方法是做类似......
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Image scaled = img.getScaledInstance(getWidth(), getHeight(), Image.SCALE_SMOOTH);
g.drawImage(scaled, 0, 0, null);
}
这是低效、昂贵的,并且可能不会产生预期的结果
首先,看看Image.getScaledInstance() 的风险
您还可以查看Java:维护 JPanel 背景图像的纵横比,以获取有关维护图像纵横比和缩放以适应与缩放以填充的更多详细信息。
我还会缓冲结果,这样您就不会在paintComponent
可能经常被捕获的方法内重复缩放图像......
更新了工作示例
这对我来说很好......
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.HeadlessException;
import java.awt.Image;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class TestImagePane {
public static void main(String[] args) {
new TestImagePane();
}
public TestImagePane() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
try {
Image img = null;
img = ImageIO.read(new File("/path/to/image"));
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new ImagePanel(img));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
} catch (IOException | HeadlessException exp) {
exp.printStackTrace();
}
}
});
}
class ImagePanel extends JPanel {
private static final long serialVersionUID = 1L;
private Image img;
private Image scaled;
public ImagePanel(String img) {
this(new ImageIcon(img).getImage());
}
public ImagePanel(Image img) {
this.img = img;
}
@Override
public void invalidate() {
super.invalidate();
int width = getWidth();
int height = getHeight();
if (width > 0 && height > 0) {
scaled = img.getScaledInstance(getWidth(), getHeight(), Image.SCALE_SMOOTH);
}
}
@Override
public Dimension getPreferredSize() {
return img == null ? new Dimension(200, 200) : new Dimension(img.getWidth(this), img.getHeight(this));
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(scaled, 0, 0, null);
}
}
}