我想在图像上附加粗体文本,只有选定的文本应该是粗体。
String word="这是虚拟文本,应该是粗体"
final BufferedImage image = ImageIO.read(new File(Background));
Graphics g = image.getGraphics();
g.drawString(word, curX, curY);
g.dispose();
ImageIO.write(image, "bmp", new File("output.bmp"));
我想在图像上附加粗体文本,只有选定的文本应该是粗体。
String word="这是虚拟文本,应该是粗体"
final BufferedImage image = ImageIO.read(new File(Background));
Graphics g = image.getGraphics();
g.drawString(word, curX, curY);
g.dispose();
ImageIO.write(image, "bmp", new File("output.bmp"));
您想使用 anAttributedString并将其传递iterator给drawString
static String Background = "input.png";
static int curX = 10;
static int curY = 50;
public static void main(String[] args) throws Exception {
AttributedString word= new AttributedString("This is text. This should be BOLD");
word.addAttribute(TextAttribute.FONT, new Font("TimesRoman", Font.PLAIN, 18));
word.addAttribute(TextAttribute.FOREGROUND, Color.BLACK);
// Sets the font to bold from index 29 (inclusive)
// to index 33 (exclusive)
word.addAttribute(TextAttribute.FONT, new Font("TimesRoman", Font.BOLD, 18), 29,33);
word.addAttribute(TextAttribute.FOREGROUND, Color.BLUE, 29,33);
final BufferedImage image = ImageIO.read(new File(Background));
Graphics g = image.getGraphics();
g.drawString(word.getIterator(), curX, curY);
g.dispose();
ImageIO.write(image, "png", new File("output.png"));
}
输出.png:

您可以在绘制 String 之前在 Graphics 对象上设置 Font,如下所示:
Font test = new Font("Arial",Font.BOLD,20);
g.setFont(test);
如果你只想要一个单词粗体,你将不得不调用 drawString 两次,并且第二次将字体设置为粗体。
也许这个会有所帮助 - curX,curY 应该在第一个 drawString 之后更新,否则它看起来会很讨厌。:)
String word="This is text, this should be ";
final BufferedImage image = ImageIO.read(new File(Background));
Graphics g = image.getGraphics();
g.drawString(word, curX, curY);
Font f = new Font("TimesRoman", Font.Bold, 72);
g.setFont(f);
String word="BOLD";
g.drawString(word, curX, curY);
g.dispose();
ImageIO.write(image, "bmp", new File("output.bmp"));