3

我正在使用 Java2DTextLayout类以及 aLineBreakMeasurer和 anAttributedCharacterIterator将一段文本绘制到一个框中。文本被换行。

分析显示代码非常慢。大部分时间都迷失在方法中TextLayout.draw(..)

有人对提高速度有建议吗?

    // Get iterator for string
    AttributedCharacterIterator iterator = attribText.getIterator();

    // Create measurer
    LineBreakMeasurer measurer = new LineBreakMeasurer(iterator, context);

    // loop over the lines
    int i = 1;
    while (measurer.getPosition() < iterator.getEndIndex()) {
        // Get line
        TextLayout textLayout = measurer.nextLayout(w);

        // get measurements
        float ascent  = textLayout.getAscent();
        float descent = textLayout.getDescent();
        float leading = textLayout.getLeading();
        float size    = ascent + descent;

        // Move down to baseline
        if( i == 1 ) {
            if( coverType == CoverType.SPINE ) {
                y = (box.height-size)/2;
                y -= (size+leading)*(lines-1)/2;
            } else if( vAlign == Alignment.Center ) {
                y += (h-size)/2-(size+leading)*(lines-1)/2;
            } else if( vAlign == Alignment.Bottom ) {
                y += (h-size) - (size+leading)*(lines-1);
            }
        }
        y += ascent;

        // calculate starting point for alignment
        float paintX = x;
        switch( hAlign ) {
            case Right: {
                paintX = x + w - textLayout.getVisibleAdvance();
                break;
            }
            case Center: {
                paintX = x + (w - textLayout.getVisibleAdvance())/2;
                break;
            }
        }

        // Draw line
        textLayout.draw(g2d, paintX, y);

        // Move down to top of next line
        y += descent + leading;
        i++;
    }

相关代码片段如上所示。attribTextAttributtedString之前的一套。contextg2d.getFontRenderContext()

4

1 回答 1

0

这篇文章现在已经相当老了,所以我希望你找到了一个适合你需求的解决方案。如果你还没有这里是需要考虑的事情。您只需要绘制可见区域内的文本。由于您知道每条线的 y 坐标,因此很容易检查 y 是否位于 getVisibleRect() 的范围内。仅绘制必要的文本会大大提高性能(当然假设您的文本比单页长)。

于 2011-01-04T04:39:34.680 回答