setBackground() 方法不适用于 Graphics2D 对象

setBackground() method is not working for Graphics2D object

我需要一些有关 Graphics2D 的帮助 class,我不确定为什么 setBackground() 方法不起作用,渲染的图像背景仍然存在白色.

int width = 128, height = 32;

BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);

Graphics2D ig2 = bi.createGraphics();
Font font = new Font("TimesRoman", Font.BOLD, 12);
ig2.setBackground(Color.BLACK);
ig2.setFont(font);
String message = "custom text";
FontMetrics fontMetrics = ig2.getFontMetrics();
int stringWidth = fontMetrics.stringWidth(message);
int stringHeight = fontMetrics.getAscent();
ig2.setPaint(Color.red);
ig2.drawString(message, stringWidth - width/2, height / 4 + stringHeight / 6);

ImageIO.write(bi, "PNG", new File("src/output.jpeg"));

谢谢你们抽出时间

您从未填充图像或绘制任何填充形状。设置背景颜色不会改变图像,它只会选择将用于下一个填充背景颜色的操作的颜色。这就像把颜料放在画笔上,但永远不会在 canvas 上作画。但是作为 clearRect say, you should use setColor followed by fillRect 的文档。

您计算在屏幕上绘制字符串的位置的方式似乎也有问题。您使用 stringWidth - width/2。宽度为 128。假设 stringWidth 为 32。那么它将是 32 - 128/2,或 32 - 64,或 -32。根据字符串的宽度,至少有一部分会绘制在缓冲图像之外。它将被剪裁,或者不可见,或者仅部分可见。

我建议 width/2 - stringWidth/2(或 (width - stringWidth)/2)。想法是从图像的中心 width/2 开始,向后退回字符串宽度的一半,使其位于图像的中心。虽然,我不知道你打算如何看待结果。