在 Java 中绘制段落时更改字体

Changing font while drawing paragraph in Java

我正在渲染一个段落,为了自动换行,我使用了 LineBreakMeasurerTextLayout class。 这是我正在使用的片段,可以轻松在线获得:

 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() 时,它按预期工作。

请提前帮我解决这个问题problem.Thank。

在您的 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());