views:

15

answers:

0

I'm using the Java2D TextLayout class together with a LineBreakMeasurer and an AttributedCharacterIterator to draw a piece of text into a box. The text is wrapped.

Profiling shows me that the code is very slow. Most of the time is lost in the method TextLayout.draw(..).

Does anyone have a suggestion for speed improvement?

    // 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++;
    }

The relevant code snippet is shown above. attribText is an AttributtedString set before. context is the g2d.getFontRenderContext().