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

The following examples show how to use java.awt.font.LineBreakMeasurer#nextLayout() . 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: MainPanel.java    From java-swing-tips with MIT License 6 votes vote down vote up
@Override protected void paintComponent(Graphics g) {
  Graphics2D g2 = (Graphics2D) g.create();
  g2.setPaint(getForeground());
  Insets i = getInsets();
  float x = i.left;
  float y = i.top;
  int w = getWidth() - i.left - i.right;
  AttributedString as = new AttributedString(getText());
  as.addAttribute(TextAttribute.FONT, getFont());
  AttributedCharacterIterator aci = as.getIterator();
  FontRenderContext frc = g2.getFontRenderContext();
  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();
  }
  g2.dispose();
}
 
Example 2
Source File: WordBreakingLineIterator.java    From pentaho-reporting with GNU Lesser General Public License v2.1 6 votes vote down vote up
private TextLayout performWordBreak( final int start, final TextLayout textLayout,
    final LineBreakMeasurer lineBreakMeasurer, final int end ) {
  final TextLayout layout;
  if ( wordInstance.isBoundary( end ) != false ) {
    return textLayout;
  }

  int preceding = wordInstance.preceding( end );
  if ( preceding == start ) {
    // single word does not fit on the line, so print full word
    lineBreakMeasurer.setPosition( start );
    return lineBreakMeasurer.nextLayout( INFINITY, wordInstance.following( end ), false );
  } else {
    lineBreakMeasurer.setPosition( start );
    return lineBreakMeasurer.nextLayout( INFINITY, preceding, false );
  }
}
 
Example 3
Source File: Test.java    From tribaltrouble with GNU General Public License v2.0 6 votes vote down vote up
private final static void pixelDataFromString(int width, int height, String str, java.awt.Font font, int[] pixels, LineBreakMeasurer measurer) {
	measurer.setPosition(0);
	g2d.clearRect(0, 0, width, height);
	g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
	g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
	float wrapping_width = width;
	float y = 0;
	int length = str.length();
	while (measurer.getPosition() < length) {
		TextLayout layout = measurer.nextLayout(wrapping_width);
		y += (layout.getAscent());
		float x = layout.isLeftToRight() ? 0 : (wrapping_width - layout.getAdvance());

		layout.draw(g2d, x, y);
		y += layout.getDescent() + layout.getLeading();
	}
	image.getRaster().getDataElements(0, 0, image.getWidth(), image.getHeight(), pixels);
}
 
Example 4
Source File: DefaultProcessDiagramCanvas.java    From activiti6-boot2 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;
     int textY = (int) 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, textY);
   	  textY += tl.getDescent() + tl.getLeading() + (interline - 1.0f) * tl.getAscent();
     }
 
     // restore originals
     g.setFont(originalFont);
     g.setPaint(originalPaint);
   }
 }
 
Example 5
Source File: FreeColToolTipUI.java    From freecol with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void paint(Graphics g, JComponent c) {
    if (c.isOpaque()) {
        ImageLibrary.drawTiledImage("image.background.FreeColToolTip",
                                    g, c, null);
    }

    g.setColor(Color.BLACK); // FIXME: find out why this is necessary

    Graphics2D graphics = (Graphics2D)g;
    float x = margin;
    float y = margin;
    for (String line : lineBreak.split(((JToolTip) c).getTipText())) {
        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);

            y += (layout.getAscent());
            float dx = layout.isLeftToRight() ?
                0 : (maximumWidth - layout.getAdvance());

            layout.draw(graphics, x + dx, y);
            y += layout.getDescent() + layout.getLeading();
        }
    }
 }
 
Example 6
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 7
Source File: TestLineBreakWithFontSub.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public void test() {

        // construct a paragraph as follows: MIXED + [SPACING + WORD] + ...
        StringBuffer text = new StringBuffer(MIXED);
        for (int i=0; i < NUM_WORDS; i++) {
            text.append(SPACING);
            text.append(WORD);
        }

        AttributedString attrString = new AttributedString(text.toString());
        attrString.addAttribute(TextAttribute.SIZE, new Float(24.0));

        LineBreakMeasurer measurer = new LineBreakMeasurer(attrString.getIterator(),
                                                           DEFAULT_FRC);

        // get width of a space-word sequence, in context
        int sequenceLength = WORD.length()+SPACING.length();
        measurer.setPosition(text.length() - sequenceLength);

        TextLayout layout = measurer.nextLayout(10000.0f);

        if (layout.getCharacterCount() != sequenceLength) {
            throw new Error("layout length is incorrect!");
        }

        final float sequenceAdvance = layout.getVisibleAdvance();

        float wrappingWidth = sequenceAdvance * 2;

        // now run test with a variety of widths
        while (wrappingWidth < (sequenceAdvance*NUM_WORDS)) {
            measurer.setPosition(0);
            checkMeasurer(measurer,
                          wrappingWidth,
                          sequenceAdvance,
                          text.length());
            wrappingWidth += sequenceAdvance / 5;
        }
    }
 
Example 8
Source File: TestLineBreakWithFontSub.java    From openjdk-jdk9 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 9
Source File: ComplexTextLineWrapper.java    From jasperreports with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public TextLine baseTextLine(int index)
{
	AttributedString tmpText = new AttributedString(paragraph, index, index + 1);
	LineBreakMeasurer lbm = new LineBreakMeasurer(tmpText.getIterator(), context.getFontRenderContext());
	TextLayout tlyt = lbm.nextLayout(100);//FIXME what is this? why 100?
	return new TextLayoutLine(tlyt);
}
 
Example 10
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 11
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 12
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 13
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 14
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 15
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 16
Source File: DefaultCaseDiagramCanvas.java    From flowable-engine 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<>();
    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 17
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 18
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 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: 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();
}