2013-05-28 4 views
0

Я хочу добавить жирный текст в изображение, только выделенный текст должен быть полужирным.Полужирный текст на изображении

Строка слово = «Этот фиктивный текст, то это должно быть BOLD»

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")); 

ответ

2

Вы хотите использовать AttributedString и передать его 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")); 
} 

output.png:

This is text. This should be BOLD

1

Вы можете установить шрифт на объект Графического, прежде чем рисовать строку, как это:

Font test = new Font("Arial",Font.BOLD,20);

g.setFont(test);

Если вам нужно только одно слово смелое, вам придется дважды вызовите drawString и установите шрифт полужирным шрифтом только второй раз.

+0

Это делает весь текст полужирным шрифтом. Мне нужен только выделенный текст, должен быть полужирным шрифтом –

0

Возможно, этот поможет - 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")); 
Смежные вопросы