如何使用BufferedImage更改图像上文本的颜色?

时间:2015-07-07 13:14:37

标签: java graphics bufferedimage

使用BufferedImage bgImage我想为图像上的文字设置黑色。

BufferedImage bgImage = createBgImageForText();
bgImage.createGraphics().drawString(player.getPlayerName(), 25, 15);
if ("Y".equalsIgnoreCase(player.getCaptain())) {
    bgImage.createGraphics().setPaint(Color.BLACK);
} else {
    bgImage.createGraphics().setPaint(Color.WHITE);
}

mainImg.getGraphics().drawImage(bgImage, 10, 10, null);

但默认情况下,文字始终为白色。 如何更改文字的颜色?

1 个答案:

答案 0 :(得分:4)

您需要存储使用Graphics创建的bgImage.createGraphics()实例,然后在绘制文本之前设置颜色

BufferedImage bgImage = createBgImageForText();
Graphics2D g = bgImage.createGraphics();
if ("Y".equalsIgnoreCase(player.getCaptain())) {
    g.setPaint(Color.BLACK);
} else {
    g.setPaint(Color.WHITE);
}
g.drawString(player.getPlayerName(), 25, 15);
g.dispose();