绘制多行文本

如果您有一段样式的文本想要适合特定的宽度,则可以使用LineBreakMeasurer类。此类使样式化的文本可以分成几行,以使它们适合特定的视觉效果。每行均以TextLayout对象的形式返回,该对象表示不可更改的样式字符数据。但是,此类也允许访问布局信息。 TextLayoutgetAscentgetDescent方法返回有关用于在组件中放置线条的字体的信息。文本存储为AttributedCharacterIterator对象,因此字体和磅值属性可以与文本一起存储。

以下 Servlets 使用LineBreakMeasurerTextLayoutAttributedCharacterIterator在组件中放置样式文本的段落。

Note:

如果看不到 Servlets 正在运行,则需要至少安装Java SE 开发套件(JDK)7版本。

此 Servlets 的完整代码在LineBreakSample.java中。

以下代码使用字符串vanGogh创建一个迭代器。检索迭代器的开始和结束,并从迭代器创建一个新的LineBreakMeasurer

AttributedCharacterIterator paragraph = vanGogh.getIterator();
    paragraphStart = paragraph.getBeginIndex();
    paragraphEnd = paragraph.getEndIndex();
    FontRenderContext frc = g2d.getFontRenderContext();
    lineMeasurer = new LineBreakMeasurer(paragraph, frc);

窗口的大小用于确定该行应在何处中断。还会为段落中的每一行创建一个TextLayout对象。

// Set break width to width of Component.
float breakWidth = (float)getSize().width;
float drawPosY = 0;
// Set position to the index of the first
// character in the paragraph.
lineMeasurer.setPosition(paragraphStart);

// Get lines from until the entire paragraph
// has been displayed.
while (lineMeasurer.getPosition() < paragraphEnd) {

    TextLayout layout = lineMeasurer.nextLayout(breakWidth);

    // Compute pen x position. If the paragraph
    // is right-to-left we will align the
    // TextLayouts to the right edge of the panel.
    float drawPosX = layout.isLeftToRight()
        ? 0 : breakWidth - layout.getAdvance();

    // Move y-coordinate by the ascent of the
    // layout.
    drawPosY += layout.getAscent();

    // Draw the TextLayout at (drawPosX,drawPosY).
    layout.draw(g2d, drawPosX, drawPosY);

    // Move y-coordinate in preparation for next
    // layout.
    drawPosY += layout.getDescent() + layout.getLeading();
}

TextLayout类不经常由应用程序直接创建。但是,当应用程序需要直接处理在文本的特定位置应用了样式(文本属性)的文本时,此类非常有用。例如,要绘制一个以斜体显示的单词,应用程序将需要执行测量并为每个子字符串 设置字体。如果文本是 Double 向的,则正确完成此任务并不容易。从AttributedString对象创建TextLayout对象可以为您解决此问题。有关TextLayout的更多信息,请查阅 Java SE 规范。