2017-02-22 33 views
1

我正在渲染一个段落,并且对于单词换行,我使用的是LineBreakMeasurerTextLayout类。 这是我使用的代码段,这是容易获得在线:在Java中绘制段落时更改字体

void drawParagraph(Graphics2D g, String paragraph, float width) { 
    LineBreakMeasurer linebreaker = new LineBreakMeasurer(new AttributedString(paragraph) 
     .getIterator(), g.getFontRenderContext()); 

    int y = 0; 
    while (linebreaker.getPosition() < paragraph.length()) { 
     TextLayout textLayout = linebreaker.nextLayout(width); 

     y += textLayout.getAscent(); 
     textLayout.draw(g, 0, y); 
     y += textLayout.getDescent() + textLayout.getLeading(); 
    } 
    } 

不过,我面临的一个问题,当我试图改变字体。 虽然我通过调用g.setFont(new Font(...))来更改字体,但该段落不会以该字体呈现。但是,当我尝试使用g.drawString()时,它按预期工作。

请帮我解决这个问题。谢谢你提前。

回答

0

在您的AttributedString中设置字体。例如:

AttributedString text = new AttributedString(paragraph); 

Font emphasis = new Font(Font.SERIF, Font.BOLD, 12); 
int emphasisStart = 30; 
int emphasisEnd = 42; 
text.addAttribute(TextAttribute.FONT, emphasis, emphasisStart, emphasisEnd); 

LineBreakMeasurer linebreaker = 
    new LineBreakMeasurer(text.getIterator(), g.getFontRenderContext());