比如说在我的程序中,我有这个paint()方法。我的愿望是创建所绘制的矩形的图像(使用 for 循环)。我尝试了下面的方法,它确实给了我那些矩形(蓝色),但背景是全黑的。当我运行程序而不创建图像,仅在 JFrame 上绘制矩形时,背景为白色。我怎样才能解决这个问题。 ?
public void paint(Graphics g) {
super.paint(g);
BufferedImage image = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB);
g = Image.getGraphics(); <<<----- is this correct?
g.setColor(Color.blue);
for ( ..... ) {
g.fillRect(X , Y, width , height);
....
}
try {
ImageIO.write(image, "jpg", new File("CustomImage.jpg"));
}catch (IOException e) {
e.printStackTrace();
}
}
图像中的背景为黑色,因为除了矩形中的像素之外,您没有为任何像素指定值。这BufferedImage
从每个像素的 RGB 为 (0, 0, 0) 开始,即黑色。要为整个图像提供白色背景,只需用白色填充图像的整个矩形即可。
BufferedImage image = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB);
g = image.createGraphics(); // not sure on this line, but this seems more right
g.setColor(Color.white);
g.fillRect(0, 0, 100, 100); // give the whole image a white background
g.setColor(Color.blue);
for( ..... ){
g.fillRect(X , Y, width , height );
....
}
请注意,我的答案是将图像写入具有白色背景的文件,而不是绘制到具有黑色背景的 JFrame。我不太确定你想要哪一个。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)