这是合并 Image 数组的一种方法。
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import javax.swing.JPanel;
class MyPanel extends JPanel {
BufferedImage image;
public MyPanel(Image[] layers) {
this.image = createBufferedImage(layers);
}
protected BufferedImage createBufferedImage(Image[] layers) {
Dimension maxSize = new Dimension();
for (int i = 0; i < layers.length; i++) {
Dimension d = new Dimension(layers[i].getWidth(this),
layers[i].getHeight(this));
maxSize = max(maxSize, d);
}
image = new BufferedImage(maxSize.width, maxSize.height,
BufferedImage.TYPE_INT_ARGB);
Graphics g = image.getGraphics();
g.setColor(Color.WHITE);
g.fillRect(0, 0, image.getWidth(), image.getHeight());
for (int i = 0; i < layers.length; i++) {
g.drawImage(layers[i], 0, 0, this);
}
g.dispose();
return image;
}
protected Dimension max(Dimension a, Dimension b) {
Dimension d = new Dimension();
d.width = Math.max(a.width, b.width);
d.height = Math.max(a.height, b.height);
return d;
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, this);
}
}