Java Code Examples for java.awt.font.LineBreakMeasurer#getPosition()

The following examples show how to use java.awt.font.LineBreakMeasurer#getPosition() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DefaultProcessDiagramCanvas.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
public void drawLabel(String text, GraphicInfo graphicInfo, boolean centered) {
    float interline = 1.0f;

    // text
    if (text != null && text.length() > 0) {
        Paint originalPaint = g.getPaint();
        Font originalFont = g.getFont();

        g.setPaint(LABEL_COLOR);
        g.setFont(LABEL_FONT);

        int wrapWidth = 100;
        double textY = graphicInfo.getY();

        // TODO: use drawMultilineText()
        AttributedString as = new AttributedString(text);
        as.addAttribute(TextAttribute.FOREGROUND, g.getPaint());
        as.addAttribute(TextAttribute.FONT, g.getFont());
        AttributedCharacterIterator aci = as.getIterator();
        FontRenderContext frc = new FontRenderContext(null, true, false);
        LineBreakMeasurer lbm = new LineBreakMeasurer(aci, frc);

        while (lbm.getPosition() < text.length()) {
            TextLayout tl = lbm.nextLayout(wrapWidth);
            textY += tl.getAscent();
            Rectangle2D bb = tl.getBounds();
            double tX = graphicInfo.getX();
            if (centered) {
                tX += (int) (graphicInfo.getWidth() / 2 - bb.getWidth() / 2);
            }
            tl.draw(g, (float) tX, (float) textY);
            textY += tl.getDescent() + tl.getLeading() + (interline - 1.0f) * tl.getAscent();
        }

        // restore originals
        g.setFont(originalFont);
        g.setPaint(originalPaint);
    }
}
 
Example 2
Source File: TestLineBreakWithFontSub.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Iterate through measurer and check that every line is
 * not too long and not too short, but just right.
 */
private void checkMeasurer(LineBreakMeasurer measurer,
                           float wrappingWidth,
                           float sequenceAdvance,
                           int endPosition) {

    do {
        TextLayout layout = measurer.nextLayout(wrappingWidth);
        float visAdvance = layout.getVisibleAdvance();

        // Check that wrappingWidth-sequenceAdvance < visAdvance
        // Also, if we're not at the end of the paragraph,
        // check that visAdvance <= wrappingWidth

        if (visAdvance > wrappingWidth) {
            // line is too long for given wrapping width
            throw new Error("layout is too long");
        }

        if (measurer.getPosition() < endPosition) {
            if (visAdvance <= wrappingWidth - sequenceAdvance) {
                // line is too short for given wrapping width;
                // another word would have fit
                throw new Error("room for more words on line.  diff=" +
                                (wrappingWidth - sequenceAdvance - visAdvance));
            }
        }
    } while (measurer.getPosition() != endPosition);
}
 
Example 3
Source File: TextArea.java    From pdfxtk with Apache License 2.0 5 votes vote down vote up
void rescale(double scale) {
     Rectangle bounds = getBounds(scale);

     HashMap settings = new HashMap();
     settings.put(TextAttribute.FONT, new Font(style.getFontAttributes(scale)));
     
     AttributedCharacterIterator par = (new AttributedString(element.getAttribute("text"), settings)).getIterator();
     LineBreakMeasurer lbm = new LineBreakMeasurer(par, new FontRenderContext(null, false, false));
     
     ArrayList drawList = new ArrayList();
     
     int parEnd   = par.getEndIndex();
     
     int positionX;
     int positionY = bounds.y;
     lbm.setPosition(par.getBeginIndex());
     while (lbm.getPosition() < parEnd) {
TextLayout layout = lbm.nextLayout(bounds.width);
positionX = bounds.x;
if (!layout.isLeftToRight()) {
  positionX += bounds.width - (int) layout.getAdvance();
}
positionY += layout.getAscent();
if (positionY > bounds.y+bounds.height) break;
drawList.add(new Point(positionX, positionY));
drawList.add(layout);
positionY += layout.getDescent() + layout.getLeading();
     }
     
     textPositions = new Point[drawList.size()/2];
     textLines     = new TextLayout[drawList.size()/2];
     textScale     = scale;

     for (int i = 0; i < textPositions.length; i++) {
textPositions[i] = (Point)      drawList.get(i*2);
textLines[i]     = (TextLayout) drawList.get(i*2+1);
     }
   }
 
Example 4
Source File: FreeColToolTipUI.java    From freecol with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Dimension getPreferredSize(JComponent c) {
    String tipText = ((JToolTip)c).getTipText();
    if (tipText == null || tipText.isEmpty()) {
        return new Dimension(0, 0);
    }

    float x = 0f;
    float y = 0f;
    for (String line : lineBreak.split(tipText)) {
        if (line.isEmpty()) {
            y += LEADING;
            continue;
        }
        AttributedCharacterIterator styledText
            = new AttributedString(line).getIterator();
        LineBreakMeasurer measurer = new LineBreakMeasurer(styledText, frc);

        while (measurer.getPosition() < styledText.getEndIndex()) {

            TextLayout layout = measurer.nextLayout(maximumWidth);

            x = Math.max(x, layout.getVisibleAdvance());
            y += layout.getAscent() + layout.getDescent() + layout.getLeading();

        }
    }
    return new Dimension((int) (x + 2 * margin),
                         (int) (y + 2 * margin));

}
 
Example 5
Source File: FontPanel.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
private void calcFontMetrics( Graphics2D g2d, int w, int h ) {
    FontMetrics fm;
    Graphics2D g2 = (Graphics2D)g2d.create();

    /// ABP
    if ( g2Transform != NONE && textToUse != FILE_TEXT ) {
        g2.setFont( g2.getFont().deriveFont( getAffineTransform( g2Transform )) );
        fm = g2.getFontMetrics();
    }
    else {
        fm = g2.getFontMetrics();
    }

    maxAscent = fm.getMaxAscent();
    maxDescent = fm.getMaxDescent();
    if (maxAscent == 0) maxAscent = 10;
    if (maxDescent == 0) maxDescent = 5;
    if ( textToUse == RANGE_TEXT || textToUse == ALL_GLYPHS ) {
        /// Give slight extra room for each character
        maxAscent += 3;
        maxDescent += 3;
        gridWidth = fm.getMaxAdvance() + 6;
        gridHeight = maxAscent + maxDescent;
        if ( force16Cols )
          numCharAcross = 16;
        else
          numCharAcross = ( w - 10 ) / gridWidth;
        numCharDown = ( h - 10 ) / gridHeight;

        canvasInset_X = ( w - numCharAcross * gridWidth ) / 2;
        canvasInset_Y = ( h - numCharDown * gridHeight ) / 2;
        if ( numCharDown == 0 || numCharAcross == 0 )
          throw new CannotDrawException( isPrinting ? CANT_FIT_PRINT : CANT_FIT_DRAW );

        if ( !isPrinting )
          resetScrollbar( verticalBar.getValue() * numCharAcross );
    }
    else {
        maxDescent += fm.getLeading();
        canvasInset_X = 5;
        canvasInset_Y = 5;
        /// gridWidth and numCharAcross will not be used in this mode...
        gridHeight = maxAscent + maxDescent;
        numCharDown = ( h - canvasInset_Y * 2 ) / gridHeight;

        if ( numCharDown == 0 )
          throw new CannotDrawException( isPrinting ? CANT_FIT_PRINT : CANT_FIT_DRAW );
        /// If this is text loaded from file, prepares the LineBreak'ed
        /// text layout at this point
        if ( textToUse == FILE_TEXT ) {
            if ( !isPrinting )
              f2dt.fireChangeStatus( "LineBreaking Text... Please Wait", false );
            lineBreakTLs = new Vector();
            for ( int i = 0; i < fileText.length; i++ ) {
                AttributedString as =
                  new AttributedString( fileText[i], g2.getFont().getAttributes() );

                LineBreakMeasurer lbm =
                  new LineBreakMeasurer( as.getIterator(), g2.getFontRenderContext() );

                while ( lbm.getPosition() < fileText[i].length() )
                  lineBreakTLs.add( lbm.nextLayout( (float) w ));

            }
        }
        if ( !isPrinting )
          resetScrollbar( verticalBar.getValue() );
    }
}
 
Example 6
Source File: ProcessDiagramCanvas.java    From activiti-in-action-codes with Apache License 2.0 4 votes vote down vote up
protected void drawMultilineText(String text, int x, int y, int boxWidth, int boxHeight) {
    int availableHeight = boxHeight - ICON_SIZE - ICON_PADDING;

    // Create an attributed string based in input text
    AttributedString attributedString = new AttributedString(text);
    attributedString.addAttribute(TextAttribute.FONT, g.getFont());
    attributedString.addAttribute(TextAttribute.FOREGROUND, Color.black);

    AttributedCharacterIterator characterIterator = attributedString.getIterator();

    int width = boxWidth - (2 * TEXT_PADDING);

    int currentHeight = 0;
    // Prepare a list of lines of text we'll be drawing
    List<TextLayout> layouts = new ArrayList<TextLayout>();
    String lastLine = null;

    LineBreakMeasurer measurer = new LineBreakMeasurer(characterIterator, g.getFontRenderContext());

    TextLayout layout = null;
    while (measurer.getPosition() < characterIterator.getEndIndex() && currentHeight <= availableHeight) {

        int previousPosition = measurer.getPosition();

        // Request next layout
        layout = measurer.nextLayout(width);

        int height = ((Float) (layout.getDescent() + layout.getAscent() + layout.getLeading())).intValue();

        if (currentHeight + height > availableHeight) {
            // The line we're about to add should NOT be added anymore, append three dots to previous one instead
            // to indicate more text is truncated
            layouts.remove(layouts.size() - 1);

            if (lastLine.length() >= 4) {
                lastLine = lastLine.substring(0, lastLine.length() - 4) + "...";
            }
            layouts.add(new TextLayout(lastLine, g.getFont(), g.getFontRenderContext()));
        } else {
            layouts.add(layout);
            lastLine = text.substring(previousPosition, measurer.getPosition());
            currentHeight += height;
        }
    }


    int currentY = y + ICON_SIZE + ICON_PADDING + ((availableHeight - currentHeight) / 2);
    int currentX = 0;

    // Actually draw the lines
    for (TextLayout textLayout : layouts) {

        currentY += textLayout.getAscent();
        currentX = TEXT_PADDING + x + ((width - ((Double) textLayout.getBounds().getWidth()).intValue()) / 2);

        textLayout.draw(g, currentX, currentY);
        currentY += textLayout.getDescent() + textLayout.getLeading();
    }

}
 
Example 7
Source File: FontPanel.java    From jdk8u_jdk with GNU General Public License v2.0 4 votes vote down vote up
private void calcFontMetrics( Graphics2D g2d, int w, int h ) {
    FontMetrics fm;
    Graphics2D g2 = (Graphics2D)g2d.create();

    /// ABP
    if ( g2Transform != NONE && textToUse != FILE_TEXT ) {
        g2.setFont( g2.getFont().deriveFont( getAffineTransform( g2Transform )) );
        fm = g2.getFontMetrics();
    }
    else {
        fm = g2.getFontMetrics();
    }

    maxAscent = fm.getMaxAscent();
    maxDescent = fm.getMaxDescent();
    if (maxAscent == 0) maxAscent = 10;
    if (maxDescent == 0) maxDescent = 5;
    if ( textToUse == RANGE_TEXT || textToUse == ALL_GLYPHS ) {
        /// Give slight extra room for each character
        maxAscent += 3;
        maxDescent += 3;
        gridWidth = fm.getMaxAdvance() + 6;
        gridHeight = maxAscent + maxDescent;
        if ( force16Cols )
          numCharAcross = 16;
        else
          numCharAcross = ( w - 10 ) / gridWidth;
        numCharDown = ( h - 10 ) / gridHeight;

        canvasInset_X = ( w - numCharAcross * gridWidth ) / 2;
        canvasInset_Y = ( h - numCharDown * gridHeight ) / 2;
        if ( numCharDown == 0 || numCharAcross == 0 )
          throw new CannotDrawException( isPrinting ? CANT_FIT_PRINT : CANT_FIT_DRAW );

        if ( !isPrinting )
          resetScrollbar( verticalBar.getValue() * numCharAcross );
    }
    else {
        maxDescent += fm.getLeading();
        canvasInset_X = 5;
        canvasInset_Y = 5;
        /// gridWidth and numCharAcross will not be used in this mode...
        gridHeight = maxAscent + maxDescent;
        numCharDown = ( h - canvasInset_Y * 2 ) / gridHeight;

        if ( numCharDown == 0 )
          throw new CannotDrawException( isPrinting ? CANT_FIT_PRINT : CANT_FIT_DRAW );
        /// If this is text loaded from file, prepares the LineBreak'ed
        /// text layout at this point
        if ( textToUse == FILE_TEXT ) {
            if ( !isPrinting )
              f2dt.fireChangeStatus( "LineBreaking Text... Please Wait", false );
            lineBreakTLs = new Vector();
            for ( int i = 0; i < fileText.length; i++ ) {
                AttributedString as =
                  new AttributedString( fileText[i], g2.getFont().getAttributes() );

                LineBreakMeasurer lbm =
                  new LineBreakMeasurer( as.getIterator(), g2.getFontRenderContext() );

                while ( lbm.getPosition() < fileText[i].length() )
                  lineBreakTLs.add( lbm.nextLayout( (float) w ));

            }
        }
        if ( !isPrinting )
          resetScrollbar( verticalBar.getValue() );
    }
}
 
Example 8
Source File: WordBreakingLineIterator.java    From pentaho-reporting with GNU Lesser General Public License v2.1 4 votes vote down vote up
protected TextLayout postProcess( final int start, final TextLayout textLayout,
    final LineBreakMeasurer lineBreakMeasurer ) {
  int end = lineBreakMeasurer.getPosition();
  final TextLayout layout = performWordBreak( start, textLayout, lineBreakMeasurer, end );
  return super.postProcess( start, layout, lineBreakMeasurer );
}
 
Example 9
Source File: FontPanel.java    From openjdk-8-source with GNU General Public License v2.0 4 votes vote down vote up
private void calcFontMetrics( Graphics2D g2d, int w, int h ) {
    FontMetrics fm;
    Graphics2D g2 = (Graphics2D)g2d.create();

    /// ABP
    if ( g2Transform != NONE && textToUse != FILE_TEXT ) {
        g2.setFont( g2.getFont().deriveFont( getAffineTransform( g2Transform )) );
        fm = g2.getFontMetrics();
    }
    else {
        fm = g2.getFontMetrics();
    }

    maxAscent = fm.getMaxAscent();
    maxDescent = fm.getMaxDescent();
    if (maxAscent == 0) maxAscent = 10;
    if (maxDescent == 0) maxDescent = 5;
    if ( textToUse == RANGE_TEXT || textToUse == ALL_GLYPHS ) {
        /// Give slight extra room for each character
        maxAscent += 3;
        maxDescent += 3;
        gridWidth = fm.getMaxAdvance() + 6;
        gridHeight = maxAscent + maxDescent;
        if ( force16Cols )
          numCharAcross = 16;
        else
          numCharAcross = ( w - 10 ) / gridWidth;
        numCharDown = ( h - 10 ) / gridHeight;

        canvasInset_X = ( w - numCharAcross * gridWidth ) / 2;
        canvasInset_Y = ( h - numCharDown * gridHeight ) / 2;
        if ( numCharDown == 0 || numCharAcross == 0 )
          throw new CannotDrawException( isPrinting ? CANT_FIT_PRINT : CANT_FIT_DRAW );

        if ( !isPrinting )
          resetScrollbar( verticalBar.getValue() * numCharAcross );
    }
    else {
        maxDescent += fm.getLeading();
        canvasInset_X = 5;
        canvasInset_Y = 5;
        /// gridWidth and numCharAcross will not be used in this mode...
        gridHeight = maxAscent + maxDescent;
        numCharDown = ( h - canvasInset_Y * 2 ) / gridHeight;

        if ( numCharDown == 0 )
          throw new CannotDrawException( isPrinting ? CANT_FIT_PRINT : CANT_FIT_DRAW );
        /// If this is text loaded from file, prepares the LineBreak'ed
        /// text layout at this point
        if ( textToUse == FILE_TEXT ) {
            if ( !isPrinting )
              f2dt.fireChangeStatus( "LineBreaking Text... Please Wait", false );
            lineBreakTLs = new Vector();
            for ( int i = 0; i < fileText.length; i++ ) {
                AttributedString as =
                  new AttributedString( fileText[i], g2.getFont().getAttributes() );

                LineBreakMeasurer lbm =
                  new LineBreakMeasurer( as.getIterator(), g2.getFontRenderContext() );

                while ( lbm.getPosition() < fileText[i].length() )
                  lineBreakTLs.add( lbm.nextLayout( (float) w ));

            }
        }
        if ( !isPrinting )
          resetScrollbar( verticalBar.getValue() );
    }
}
 
Example 10
Source File: FontPanel.java    From hottub with GNU General Public License v2.0 4 votes vote down vote up
private void calcFontMetrics( Graphics2D g2d, int w, int h ) {
    FontMetrics fm;
    Graphics2D g2 = (Graphics2D)g2d.create();

    /// ABP
    if ( g2Transform != NONE && textToUse != FILE_TEXT ) {
        g2.setFont( g2.getFont().deriveFont( getAffineTransform( g2Transform )) );
        fm = g2.getFontMetrics();
    }
    else {
        fm = g2.getFontMetrics();
    }

    maxAscent = fm.getMaxAscent();
    maxDescent = fm.getMaxDescent();
    if (maxAscent == 0) maxAscent = 10;
    if (maxDescent == 0) maxDescent = 5;
    if ( textToUse == RANGE_TEXT || textToUse == ALL_GLYPHS ) {
        /// Give slight extra room for each character
        maxAscent += 3;
        maxDescent += 3;
        gridWidth = fm.getMaxAdvance() + 6;
        gridHeight = maxAscent + maxDescent;
        if ( force16Cols )
          numCharAcross = 16;
        else
          numCharAcross = ( w - 10 ) / gridWidth;
        numCharDown = ( h - 10 ) / gridHeight;

        canvasInset_X = ( w - numCharAcross * gridWidth ) / 2;
        canvasInset_Y = ( h - numCharDown * gridHeight ) / 2;
        if ( numCharDown == 0 || numCharAcross == 0 )
          throw new CannotDrawException( isPrinting ? CANT_FIT_PRINT : CANT_FIT_DRAW );

        if ( !isPrinting )
          resetScrollbar( verticalBar.getValue() * numCharAcross );
    }
    else {
        maxDescent += fm.getLeading();
        canvasInset_X = 5;
        canvasInset_Y = 5;
        /// gridWidth and numCharAcross will not be used in this mode...
        gridHeight = maxAscent + maxDescent;
        numCharDown = ( h - canvasInset_Y * 2 ) / gridHeight;

        if ( numCharDown == 0 )
          throw new CannotDrawException( isPrinting ? CANT_FIT_PRINT : CANT_FIT_DRAW );
        /// If this is text loaded from file, prepares the LineBreak'ed
        /// text layout at this point
        if ( textToUse == FILE_TEXT ) {
            if ( !isPrinting )
              f2dt.fireChangeStatus( "LineBreaking Text... Please Wait", false );
            lineBreakTLs = new Vector();
            for ( int i = 0; i < fileText.length; i++ ) {
                AttributedString as =
                  new AttributedString( fileText[i], g2.getFont().getAttributes() );

                LineBreakMeasurer lbm =
                  new LineBreakMeasurer( as.getIterator(), g2.getFontRenderContext() );

                while ( lbm.getPosition() < fileText[i].length() )
                  lineBreakTLs.add( lbm.nextLayout( (float) w ));

            }
        }
        if ( !isPrinting )
          resetScrollbar( verticalBar.getValue() );
    }
}
 
Example 11
Source File: FontPanel.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
private void calcFontMetrics( Graphics2D g2d, int w, int h ) {
    FontMetrics fm;
    Graphics2D g2 = (Graphics2D)g2d.create();

    /// ABP
    if ( g2Transform != NONE && textToUse != FILE_TEXT ) {
        g2.setFont( g2.getFont().deriveFont( getAffineTransform( g2Transform )) );
        fm = g2.getFontMetrics();
    }
    else {
        fm = g2.getFontMetrics();
    }

    maxAscent = fm.getMaxAscent();
    maxDescent = fm.getMaxDescent();
    if (maxAscent == 0) maxAscent = 10;
    if (maxDescent == 0) maxDescent = 5;
    if ( textToUse == RANGE_TEXT || textToUse == ALL_GLYPHS ) {
        /// Give slight extra room for each character
        maxAscent += 3;
        maxDescent += 3;
        gridWidth = fm.getMaxAdvance() + 6;
        gridHeight = maxAscent + maxDescent;
        if ( force16Cols )
          numCharAcross = 16;
        else
          numCharAcross = ( w - 10 ) / gridWidth;
        numCharDown = ( h - 10 ) / gridHeight;

        canvasInset_X = ( w - numCharAcross * gridWidth ) / 2;
        canvasInset_Y = ( h - numCharDown * gridHeight ) / 2;
        if ( numCharDown == 0 || numCharAcross == 0 )
          throw new CannotDrawException( isPrinting ? CANT_FIT_PRINT : CANT_FIT_DRAW );

        if ( !isPrinting )
          resetScrollbar( verticalBar.getValue() * numCharAcross );
    }
    else {
        maxDescent += fm.getLeading();
        canvasInset_X = 5;
        canvasInset_Y = 5;
        /// gridWidth and numCharAcross will not be used in this mode...
        gridHeight = maxAscent + maxDescent;
        numCharDown = ( h - canvasInset_Y * 2 ) / gridHeight;

        if ( numCharDown == 0 )
          throw new CannotDrawException( isPrinting ? CANT_FIT_PRINT : CANT_FIT_DRAW );
        /// If this is text loaded from file, prepares the LineBreak'ed
        /// text layout at this point
        if ( textToUse == FILE_TEXT ) {
            if ( !isPrinting )
              f2dt.fireChangeStatus( "LineBreaking Text... Please Wait", false );
            lineBreakTLs = new Vector();
            for ( int i = 0; i < fileText.length; i++ ) {
                AttributedString as =
                  new AttributedString( fileText[i], g2.getFont().getAttributes() );

                LineBreakMeasurer lbm =
                  new LineBreakMeasurer( as.getIterator(), g2.getFontRenderContext() );

                while ( lbm.getPosition() < fileText[i].length() )
                  lineBreakTLs.add( lbm.nextLayout( (float) w ));

            }
        }
        if ( !isPrinting )
          resetScrollbar( verticalBar.getValue() );
    }
}
 
Example 12
Source File: TextArea2.java    From pdfxtk with Apache License 2.0 4 votes vote down vote up
void rescale(double scale) {
     Rectangle bounds = getBounds(scale);

     HashMap settings = new HashMap();
     
     // java 5: Float fontSize = Float.parseFloat(element.getAttribute("font-size"));
     float fontSize = Float.parseFloat(element.getAttribute("font-size"));
     
     settings.put(TextAttribute.FONT, new Font(style.getFontAttributes(scale * fontSize)));
     
     AttributedCharacterIterator par = (new AttributedString(element.getAttribute("text"), settings)).getIterator();
     
     //style.fontSize = Float.parseFloat(element.getAttribute("font-size"));
     //style.setParam(context, this, element.getAttribute("font-size"));
    // this.style("fontsize", element.getAttribute("font-size"));
     
     LineBreakMeasurer lbm = new LineBreakMeasurer(par, new FontRenderContext(null, false, false));
     
     ArrayList drawList = new ArrayList();
     
     int parEnd   = par.getEndIndex();
     
     int positionX;
     int positionY = bounds.y;
     lbm.setPosition(par.getBeginIndex());
     while (lbm.getPosition() < parEnd) {
TextLayout layout = lbm.nextLayout(bounds.width);
positionX = bounds.x;
if (!layout.isLeftToRight()) {
  positionX += bounds.width - (int) layout.getAdvance();
}
positionY += layout.getAscent();
if (positionY > bounds.y+bounds.height) break;
drawList.add(new Point(positionX, positionY));
drawList.add(layout);
positionY += layout.getDescent() + layout.getLeading();
     }
     
     textPositions = new Point[drawList.size()/2];
     textLines     = new TextLayout[drawList.size()/2];
     textScale     = scale;

     for (int i = 0; i < textPositions.length; i++) {
textPositions[i] = (Point)      drawList.get(i*2);
textLines[i]     = (TextLayout) drawList.get(i*2+1);
     }
   }
 
Example 13
Source File: StyleManagerUtils.java    From birt with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Calculate the height of a string formatted according to a set of RichTextRuns and fitted within a give width.
 * @param sourceText
 * The string to be measured.
 * @param defaultFont
 * The font to be used prior to the first RichTextRun.
 * @param widthMM
 * The width of the output.
 * @param richTextRuns
 * The list of RichTextRuns to be applied to the string
 * @return
 * The heigh, in points, of a box big enough to contain the formatted sourceText.
 */
public float calculateTextHeightPoints( String sourceText, Font defaultFont, double widthMM, List< RichTextRun> richTextRuns ) {
	log.debug( "Calculating height for ", sourceText);
	
	final float widthPt = (float)(72 * Math.max( 0, widthMM - 6 ) / 25.4); 
	
	float totalHeight = 0;
	String[] textLines = sourceText.split("\n");
	int lineStartIndex = 0;
	String lastLine = null;
	Font font = defaultFont;
	for( String textLine : textLines ) {
		if( lastLine != null ) {
			lineStartIndex += lastLine.length() + 1;
		} 
		lastLine = textLine;
		
		AttributedString attrString = new AttributedString(textLine.isEmpty() ? " " : textLine);
		int runEnd = textLine.length();
		
		int richTextRunIndex = getRichTextRunIndexForStart(richTextRuns, lineStartIndex);
		if( richTextRunIndex >= 0 ) {
			font = richTextRuns.get(richTextRunIndex).font;
			if( ( richTextRunIndex < richTextRuns.size() - 1 ) && ( richTextRuns.get(richTextRunIndex + 1).startIndex < runEnd ) ) {
				runEnd = richTextRuns.get(richTextRunIndex + 1).startIndex;
			}
		}
		
		log.debug( "Adding attribute - [", 0, " - ", runEnd, "] = ", defaultFont.getFontName(), " ", defaultFont.getFontHeightInPoints(), "pt" );
		addFontAttributes(attrString, font, 0, textLine.isEmpty() ? 1 : runEnd );

		for( ++richTextRunIndex; ( richTextRunIndex < richTextRuns.size() ) && ( richTextRuns.get( richTextRunIndex ).startIndex < lineStartIndex + textLine.length() ) ; ++richTextRunIndex ) {
			RichTextRun run = richTextRuns.get( richTextRunIndex );
			RichTextRun nextRun = richTextRunIndex < richTextRuns.size() - 1 ? richTextRuns.get( richTextRunIndex + 1) : null;
			if( ( run.startIndex >= lineStartIndex ) && ( run.startIndex < lineStartIndex + textLine.length() + 1 ) ) {
				int startIdx = run.startIndex - lineStartIndex;
				int endIdx = ( nextRun == null ? sourceText.length() : nextRun.startIndex ) - lineStartIndex;
				if( endIdx > textLine.length() ) {
					endIdx = textLine.length();
				}
				if( startIdx < endIdx ) {
					log.debug( "Adding attribute: [", startIdx, " - ", endIdx, "] = ", run.font.getFontName(), " ", run.font.getFontHeightInPoints(), "pt" );
					addFontAttributes(attrString, run.font, startIdx, endIdx );
				}
			}
		}		
		
		LineBreakMeasurer measurer = new LineBreakMeasurer( attrString.getIterator(), frc);
	    
		float heightAdjustment = 0.0F;
		int lineLength = textLine.isEmpty() ? 1 : textLine.length();
		while (measurer.getPosition() < lineLength) {
	         TextLayout layout = measurer.nextLayout( widthPt );
	         float lineHeight = layout.getAscent() + layout.getDescent() + layout.getLeading();
	         if( layout.getDescent() + layout.getLeading() > heightAdjustment ) {
	        	 heightAdjustment = layout.getDescent() + layout.getLeading();
	         }
	         log.debug ( "Line: ", textLine, " gives height ", lineHeight, "(", layout.getAscent(), "/", layout.getDescent(), "/", layout.getLeading(), ")");
	         totalHeight += lineHeight;
		}
		totalHeight += heightAdjustment;
		
	}
	log.debug( "Height calculated as ", totalHeight );
	return totalHeight;
}
 
Example 14
Source File: FontPanel.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 4 votes vote down vote up
private void calcFontMetrics( Graphics2D g2d, int w, int h ) {
    FontMetrics fm;
    Graphics2D g2 = (Graphics2D)g2d.create();

    /// ABP
    if ( g2Transform != NONE && textToUse != FILE_TEXT ) {
        g2.setFont( g2.getFont().deriveFont( getAffineTransform( g2Transform )) );
        fm = g2.getFontMetrics();
    }
    else {
        fm = g2.getFontMetrics();
    }

    maxAscent = fm.getMaxAscent();
    maxDescent = fm.getMaxDescent();
    if (maxAscent == 0) maxAscent = 10;
    if (maxDescent == 0) maxDescent = 5;
    if ( textToUse == RANGE_TEXT || textToUse == ALL_GLYPHS ) {
        /// Give slight extra room for each character
        maxAscent += 3;
        maxDescent += 3;
        gridWidth = fm.getMaxAdvance() + 6;
        gridHeight = maxAscent + maxDescent;
        if ( force16Cols )
          numCharAcross = 16;
        else
          numCharAcross = ( w - 10 ) / gridWidth;
        numCharDown = ( h - 10 ) / gridHeight;

        canvasInset_X = ( w - numCharAcross * gridWidth ) / 2;
        canvasInset_Y = ( h - numCharDown * gridHeight ) / 2;
        if ( numCharDown == 0 || numCharAcross == 0 )
          throw new CannotDrawException( isPrinting ? CANT_FIT_PRINT : CANT_FIT_DRAW );

        if ( !isPrinting )
          resetScrollbar( verticalBar.getValue() * numCharAcross );
    }
    else {
        maxDescent += fm.getLeading();
        canvasInset_X = 5;
        canvasInset_Y = 5;
        /// gridWidth and numCharAcross will not be used in this mode...
        gridHeight = maxAscent + maxDescent;
        numCharDown = ( h - canvasInset_Y * 2 ) / gridHeight;

        if ( numCharDown == 0 )
          throw new CannotDrawException( isPrinting ? CANT_FIT_PRINT : CANT_FIT_DRAW );
        /// If this is text loaded from file, prepares the LineBreak'ed
        /// text layout at this point
        if ( textToUse == FILE_TEXT ) {
            if ( !isPrinting )
              f2dt.fireChangeStatus( "LineBreaking Text... Please Wait", false );
            lineBreakTLs = new Vector();
            for ( int i = 0; i < fileText.length; i++ ) {
                AttributedString as =
                  new AttributedString( fileText[i], g2.getFont().getAttributes() );

                LineBreakMeasurer lbm =
                  new LineBreakMeasurer( as.getIterator(), g2.getFontRenderContext() );

                while ( lbm.getPosition() < fileText[i].length() )
                  lineBreakTLs.add( lbm.nextLayout( (float) w ));

            }
        }
        if ( !isPrinting )
          resetScrollbar( verticalBar.getValue() );
    }
}
 
Example 15
Source File: DrawTextParagraph.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
 * break text into lines, each representing a line of text that fits in the wrapping width
 *
 * @param graphics The drawing context for computing text-lengths.
 */
protected void breakText(Graphics2D graphics){
    lines.clear();

    DrawFactory fact = DrawFactory.getInstance(graphics);
    fact.fixFonts(graphics);
    StringBuilder text = new StringBuilder();
    AttributedString at = getAttributedString(graphics, text);
    boolean emptyParagraph = ("".equals(text.toString().trim()));

    AttributedCharacterIterator it = at.getIterator();
    LineBreakMeasurer measurer = new LineBreakMeasurer(it, graphics.getFontRenderContext());
    for (;;) {
        int startIndex = measurer.getPosition();

        // add a pixel to compensate rounding errors
        double wrappingWidth = getWrappingWidth(lines.isEmpty(), graphics) + 1;
        // shape width can be smaller that the sum of insets (this was proved by a test file)
        if(wrappingWidth < 0) {
            wrappingWidth = 1;
        }

        int nextBreak = text.indexOf("\n", startIndex + 1);
        if (nextBreak == -1) {
            nextBreak = it.getEndIndex();
        }

        TextLayout layout = measurer.nextLayout((float)wrappingWidth, nextBreak, true);
        if (layout == null) {
             // layout can be null if the entire word at the current position
             // does not fit within the wrapping width. Try with requireNextWord=false.
             layout = measurer.nextLayout((float)wrappingWidth, nextBreak, false);
        }

        if(layout == null) {
            // exit if can't break any more
            break;
        }

        int endIndex = measurer.getPosition();
        // skip over new line breaks (we paint 'clear' text runs not starting or ending with \n)
        if(endIndex < it.getEndIndex() && text.charAt(endIndex) == '\n'){
            measurer.setPosition(endIndex + 1);
        }

        TextAlign hAlign = paragraph.getTextAlign();
        if(hAlign == TextAlign.JUSTIFY || hAlign == TextAlign.JUSTIFY_LOW) {
            layout = layout.getJustifiedLayout((float)wrappingWidth);
        }

        AttributedString str = (emptyParagraph)
            ? null // we will not paint empty paragraphs
            : new AttributedString(it, startIndex, endIndex);
        DrawTextFragment line = fact.getTextFragment(layout, str);
        lines.add(line);

        maxLineHeight = Math.max(maxLineHeight, line.getHeight());

        if(endIndex == it.getEndIndex()) {
            break;
        }
    }

    rawText = text.toString();
}
 
Example 16
Source File: FontPanel.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
private void calcFontMetrics( Graphics2D g2d, int w, int h ) {
    FontMetrics fm;
    Graphics2D g2 = (Graphics2D)g2d.create();

    /// ABP
    if ( g2Transform != NONE && textToUse != FILE_TEXT ) {
        g2.setFont( g2.getFont().deriveFont( getAffineTransform( g2Transform )) );
        fm = g2.getFontMetrics();
    }
    else {
        fm = g2.getFontMetrics();
    }

    maxAscent = fm.getMaxAscent();
    maxDescent = fm.getMaxDescent();
    if (maxAscent == 0) maxAscent = 10;
    if (maxDescent == 0) maxDescent = 5;
    if ( textToUse == RANGE_TEXT || textToUse == ALL_GLYPHS ) {
        /// Give slight extra room for each character
        maxAscent += 3;
        maxDescent += 3;
        gridWidth = fm.getMaxAdvance() + 6;
        gridHeight = maxAscent + maxDescent;
        if ( force16Cols )
          numCharAcross = 16;
        else
          numCharAcross = ( w - 10 ) / gridWidth;
        numCharDown = ( h - 10 ) / gridHeight;

        canvasInset_X = ( w - numCharAcross * gridWidth ) / 2;
        canvasInset_Y = ( h - numCharDown * gridHeight ) / 2;
        if ( numCharDown == 0 || numCharAcross == 0 )
          throw new CannotDrawException( isPrinting ? CANT_FIT_PRINT : CANT_FIT_DRAW );

        if ( !isPrinting )
          resetScrollbar( verticalBar.getValue() * numCharAcross );
    }
    else {
        maxDescent += fm.getLeading();
        canvasInset_X = 5;
        canvasInset_Y = 5;
        /// gridWidth and numCharAcross will not be used in this mode...
        gridHeight = maxAscent + maxDescent;
        numCharDown = ( h - canvasInset_Y * 2 ) / gridHeight;

        if ( numCharDown == 0 )
          throw new CannotDrawException( isPrinting ? CANT_FIT_PRINT : CANT_FIT_DRAW );
        /// If this is text loaded from file, prepares the LineBreak'ed
        /// text layout at this point
        if ( textToUse == FILE_TEXT ) {
            if ( !isPrinting )
              f2dt.fireChangeStatus( "LineBreaking Text... Please Wait", false );
            lineBreakTLs = new Vector();
            for ( int i = 0; i < fileText.length; i++ ) {
                AttributedString as =
                  new AttributedString( fileText[i], g2.getFont().getAttributes() );

                LineBreakMeasurer lbm =
                  new LineBreakMeasurer( as.getIterator(), g2.getFontRenderContext() );

                while ( lbm.getPosition() < fileText[i].length() )
                  lineBreakTLs.add( lbm.nextLayout( (float) w ));

            }
        }
        if ( !isPrinting )
          resetScrollbar( verticalBar.getValue() );
    }
}
 
Example 17
Source File: MainPanel.java    From java-swing-tips with MIT License 4 votes vote down vote up
@Override protected void paintComponent(Graphics g) {
  Graphics2D g2 = (Graphics2D) g.create();
  g2.setPaint(getBackground());
  g2.fillRect(0, 0, getWidth(), getHeight());

  Insets i = getInsets();
  float x0 = i.left;
  float y0 = i.top;

  Font font = getFont();
  String txt = getText();

  FontRenderContext frc = g2.getFontRenderContext();
  Shape shape = new TextLayout(txt.substring(0, 1), font, frc).getOutline(null);

  AffineTransform at1 = AffineTransform.getScaleInstance(5d, 5d);
  Shape s1 = at1.createTransformedShape(shape);
  Rectangle r = s1.getBounds();
  r.grow(6, 2);
  int rw = r.width;
  int rh = r.height;

  AffineTransform at2 = AffineTransform.getTranslateInstance(x0, y0 + rh);
  Shape s2 = at2.createTransformedShape(s1);
  g2.setPaint(getForeground());
  g2.fill(s2);

  float x = x0 + rw;
  float y = y0;
  int w0 = getWidth() - i.left - i.right;
  int w = w0 - rw;

  AttributedString as = new AttributedString(txt.substring(1));
  as.addAttribute(TextAttribute.FONT, font);
  AttributedCharacterIterator aci = as.getIterator();
  LineBreakMeasurer lbm = new LineBreakMeasurer(aci, frc);
  while (lbm.getPosition() < aci.getEndIndex()) {
    TextLayout tl = lbm.nextLayout(w);
    tl.draw(g2, x, y + tl.getAscent());
    y += tl.getDescent() + tl.getLeading() + tl.getAscent();
    if (y0 + rh < y) {
      x = x0;
      w = w0;
    }
  }
  g2.dispose();
}
 
Example 18
Source File: DefaultProcessDiagramCanvas.java    From activiti6-boot2 with Apache License 2.0 4 votes vote down vote up
protected void drawMultilineText(String text, int x, int y, int boxWidth, int boxHeight, boolean centered) {
  // Create an attributed string based in input text
  AttributedString attributedString = new AttributedString(text);
  attributedString.addAttribute(TextAttribute.FONT, g.getFont());
  attributedString.addAttribute(TextAttribute.FOREGROUND, Color.black);
  
  AttributedCharacterIterator characterIterator = attributedString.getIterator();
  
  int currentHeight = 0;
  // Prepare a list of lines of text we'll be drawing
  List<TextLayout> layouts = new ArrayList<TextLayout>();
  String lastLine = null;
  
  LineBreakMeasurer measurer = new LineBreakMeasurer(characterIterator, g.getFontRenderContext());
  
  TextLayout layout = null;
  while (measurer.getPosition() < characterIterator.getEndIndex() && currentHeight <= boxHeight) {
     
    int previousPosition = measurer.getPosition();
    
    // Request next layout
    layout = measurer.nextLayout(boxWidth);
    
    int height = ((Float)(layout.getDescent() + layout.getAscent() + layout.getLeading())).intValue();
    
    if(currentHeight + height > boxHeight) {
      // The line we're about to add should NOT be added anymore, append three dots to previous one instead
      // to indicate more text is truncated
      if (!layouts.isEmpty()) {
        layouts.remove(layouts.size() - 1);
        
        if(lastLine.length() >= 4) {
          lastLine = lastLine.substring(0, lastLine.length() - 4) + "...";
        }
        layouts.add(new TextLayout(lastLine, g.getFont(), g.getFontRenderContext()));
      }
      break;
    } else {
      layouts.add(layout);
      lastLine = text.substring(previousPosition, measurer.getPosition());
      currentHeight += height;
    }
  }
  
  
  int currentY = y + (centered ? ((boxHeight - currentHeight) /2) : 0);
  int currentX = 0;
  
  // Actually draw the lines
  for(TextLayout textLayout : layouts) {
    
    currentY += textLayout.getAscent();
    currentX = x + (centered ? ((boxWidth - ((Double)textLayout.getBounds().getWidth()).intValue()) /2) : 0);
    
    textLayout.draw(g, currentX, currentY);
    currentY += textLayout.getDescent() + textLayout.getLeading();
  }
  
}
 
Example 19
Source File: ProcessDiagramCanvas.java    From activiti-in-action-codes with Apache License 2.0 4 votes vote down vote up
protected void drawMultilineText(String text, int x, int y, int boxWidth, int boxHeight) {
    int availableHeight = boxHeight - ICON_SIZE - ICON_PADDING;

    // Create an attributed string based in input text
    AttributedString attributedString = new AttributedString(text);
    attributedString.addAttribute(TextAttribute.FONT, g.getFont());
    attributedString.addAttribute(TextAttribute.FOREGROUND, Color.black);

    AttributedCharacterIterator characterIterator = attributedString.getIterator();

    int width = boxWidth - (2 * TEXT_PADDING);

    int currentHeight = 0;
    // Prepare a list of lines of text we'll be drawing
    List<TextLayout> layouts = new ArrayList<TextLayout>();
    String lastLine = null;

    LineBreakMeasurer measurer = new LineBreakMeasurer(characterIterator, g.getFontRenderContext());

    TextLayout layout = null;
    while (measurer.getPosition() < characterIterator.getEndIndex() && currentHeight <= availableHeight) {

        int previousPosition = measurer.getPosition();

        // Request next layout
        layout = measurer.nextLayout(width);

        int height = ((Float) (layout.getDescent() + layout.getAscent() + layout.getLeading())).intValue();

        if (currentHeight + height > availableHeight) {
            // The line we're about to add should NOT be added anymore, append three dots to previous one instead
            // to indicate more text is truncated
            layouts.remove(layouts.size() - 1);

            if (lastLine.length() >= 4) {
                lastLine = lastLine.substring(0, lastLine.length() - 4) + "...";
            }
            layouts.add(new TextLayout(lastLine, g.getFont(), g.getFontRenderContext()));
        } else {
            layouts.add(layout);
            lastLine = text.substring(previousPosition, measurer.getPosition());
            currentHeight += height;
        }
    }


    int currentY = y + ICON_SIZE + ICON_PADDING + ((availableHeight - currentHeight) / 2);
    int currentX = 0;

    // Actually draw the lines
    for (TextLayout textLayout : layouts) {

        currentY += textLayout.getAscent();
        currentX = TEXT_PADDING + x + ((width - ((Double) textLayout.getBounds().getWidth()).intValue()) / 2);

        textLayout.draw(g, currentX, currentY);
        currentY += textLayout.getDescent() + textLayout.getLeading();
    }

}
 
Example 20
Source File: FontPanel.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
private void calcFontMetrics( Graphics2D g2d, int w, int h ) {
    FontMetrics fm;
    Graphics2D g2 = (Graphics2D)g2d.create();

    /// ABP
    if ( g2Transform != NONE && textToUse != FILE_TEXT ) {
        g2.setFont( g2.getFont().deriveFont( getAffineTransform( g2Transform )) );
        fm = g2.getFontMetrics();
    }
    else {
        fm = g2.getFontMetrics();
    }

    maxAscent = fm.getMaxAscent();
    maxDescent = fm.getMaxDescent();
    if (maxAscent == 0) maxAscent = 10;
    if (maxDescent == 0) maxDescent = 5;
    if ( textToUse == RANGE_TEXT || textToUse == ALL_GLYPHS ) {
        /// Give slight extra room for each character
        maxAscent += 3;
        maxDescent += 3;
        gridWidth = fm.getMaxAdvance() + 6;
        gridHeight = maxAscent + maxDescent;
        if ( force16Cols )
          numCharAcross = 16;
        else
          numCharAcross = ( w - 10 ) / gridWidth;
        numCharDown = ( h - 10 ) / gridHeight;

        canvasInset_X = ( w - numCharAcross * gridWidth ) / 2;
        canvasInset_Y = ( h - numCharDown * gridHeight ) / 2;
        if ( numCharDown == 0 || numCharAcross == 0 )
          throw new CannotDrawException( isPrinting ? CANT_FIT_PRINT : CANT_FIT_DRAW );

        if ( !isPrinting )
          resetScrollbar( verticalBar.getValue() * numCharAcross );
    }
    else {
        maxDescent += fm.getLeading();
        canvasInset_X = 5;
        canvasInset_Y = 5;
        /// gridWidth and numCharAcross will not be used in this mode...
        gridHeight = maxAscent + maxDescent;
        numCharDown = ( h - canvasInset_Y * 2 ) / gridHeight;

        if ( numCharDown == 0 )
          throw new CannotDrawException( isPrinting ? CANT_FIT_PRINT : CANT_FIT_DRAW );
        /// If this is text loaded from file, prepares the LineBreak'ed
        /// text layout at this point
        if ( textToUse == FILE_TEXT ) {
            if ( !isPrinting )
              f2dt.fireChangeStatus( "LineBreaking Text... Please Wait", false );
            lineBreakTLs = new Vector();
            for ( int i = 0; i < fileText.length; i++ ) {
                AttributedString as =
                  new AttributedString( fileText[i], g2.getFont().getAttributes() );

                LineBreakMeasurer lbm =
                  new LineBreakMeasurer( as.getIterator(), g2.getFontRenderContext() );

                while ( lbm.getPosition() < fileText[i].length() )
                  lineBreakTLs.add( lbm.nextLayout( (float) w ));

            }
        }
        if ( !isPrinting )
          resetScrollbar( verticalBar.getValue() );
    }
}