java.awt.font.LineBreakMeasurer Java Examples

The following examples show how to use java.awt.font.LineBreakMeasurer. 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: 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 #2
Source File: DesenhadorDeTexto.java    From brModelo with GNU General Public License v3.0 6 votes vote down vote up
private LineBreakMeasurer[] getLineBreakMeasurers(Graphics2D g) {
    if (lbmTexto == null && (Texto != null && !Texto.equals(""))) {
        lbmTexto = new LineBreakMeasurer[Textos.length];
        for (int i = 0; i < lbmTexto.length; i++) {
            String tmp = Textos[i].isEmpty()? " " : Textos[i];
            AttributedString attribString = new AttributedString(tmp);
            attribString.addAttribute(TextAttribute.FONT, getFont());
            //attribString.addAttribute(TextAttribute.FONT, getFont());
            AttributedCharacterIterator attribCharIterator = attribString.getIterator();
            //FontRenderContext frc = new FontRenderContext(null, true, false);
            FontRenderContext frc = g.getFontRenderContext();
            lbmTexto[i] = new LineBreakMeasurer(attribCharIterator, frc);
        }
    }
    return lbmTexto;
}
 
Example #3
Source File: SimpleTextLineWrapper.java    From jasperreports with GNU Lesser General Public License v3.0 6 votes vote down vote up
protected int measureExactLineBreakIndex(float width, int endLimit, boolean requireWord)
{
	//FIXME would it be faster to create and cache a LineBreakMeasurer for the whole paragraph?
	Map<Attribute, Object> attributes = new HashMap<Attribute, Object>();
	// we only need the font as it includes the size and style
	attributes.put(TextAttribute.FONT, fontInfo.fontInfo.font);
	
	String textLine = paragraphText.substring(paragraphPosition, endLimit);
	AttributedString attributedLine = new AttributedString(textLine, attributes);

	// we need a fresh iterator for the line
	BreakIterator breakIterator = paragraphTruncateAtChar ? BreakIterator.getCharacterInstance()
			: BreakIterator.getLineInstance();
	LineBreakMeasurer breakMeasurer = new LineBreakMeasurer(attributedLine.getIterator(), 
			breakIterator, context.getFontRenderContext());
	int breakIndex = breakMeasurer.nextOffset(width, endLimit - paragraphPosition, requireWord) 
			+ paragraphPosition;
	if (logTrace)
	{
		log.trace("exact line break index measured at " + (paragraphOffset + breakIndex));
	}
	
	return breakIndex;
}
 
Example #4
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 #5
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.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
  g2.setPaint(getForeground());
  g2.setFont(getFont());

  SwingUtilities.calculateInnerArea(this, RECT);
  float x = RECT.x;
  float y = RECT.y;
  int w = RECT.width;

  AttributedString as = new AttributedString(getText());
  as.addAttribute(TextAttribute.FONT, getFont()); // TEST: .deriveFont(at));
  // TEST: as.addAttribute(TextAttribute.TRANSFORM, at);
  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 #6
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 #7
Source File: JMultilineLabel.java    From Spark with Apache License 2.0 6 votes vote down vote up
private Dimension paintOrGetSize(Graphics2D g, int width) {
    Insets insets = getInsets();
    width -= insets.left + insets.right + margin.left + margin.right;
    float w = insets.left + insets.right + margin.left + margin.right;
    float x = insets.left + margin.left, y = insets.top + margin.top;
    if (width > 0 && text != null && text.length() > 0) {
        AttributedString as = new AttributedString(getText());
        as.addAttribute(TextAttribute.FONT, getFont());
        AttributedCharacterIterator aci = as.getIterator();
        LineBreakMeasurer lbm = new LineBreakMeasurer(aci, frc);
        float max = 0;
        while (lbm.getPosition() < aci.getEndIndex()) {
            TextLayout textLayout = lbm.nextLayout(width);
            if (g != null && isJustified() && textLayout.getVisibleAdvance() > 0.80 * width)
                textLayout = textLayout.getJustifiedLayout(width);
            if (g != null)
                textLayout.draw(g, x, y + textLayout.getAscent());
            y += textLayout.getDescent() + textLayout.getLeading() + textLayout.getAscent();
            max = Math.max(max, textLayout.getVisibleAdvance());
        }
        w += max;
    }
    return new Dimension((int)Math.ceil(w), (int)Math.ceil(y) + insets.bottom + margin.bottom);
}
 
Example #8
Source File: LineBreakIterator.java    From pentaho-reporting with GNU Lesser General Public License v2.1 5 votes vote down vote up
public LineBreakIterator( ParagraphRenderBox box, FontRenderContext fontRenderContext, AttributedCharacterIterator ci ) {
  this.wrappingWidth = (float) StrictGeomUtility.toExternalValue( box.getCachedWidth() );
  this.justifiedLayout =
      ElementAlignment.JUSTIFY.equals( box.getStyleSheet().getStyleProperty( ElementStyleKeys.ALIGNMENT ) );
  this.ci = ci;
  this.lineBreakMeasurer = new LineBreakMeasurer( ci, fontRenderContext );
  this.lineBreakMeasurer.setPosition( ci.getBeginIndex() );
}
 
Example #9
Source File: LineBreakIterator.java    From pentaho-reporting with GNU Lesser General Public License v2.1 5 votes vote down vote up
protected TextLayout postProcess( final int start, final TextLayout textLayout,
    final LineBreakMeasurer lineBreakMeasurer ) {
  if ( justifiedLayout ) {
    return textLayout.getJustifiedLayout( wrappingWidth );
  } else {
    return textLayout;
  }
}
 
Example #10
Source File: GlyphVectorOutline.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
private static void drawString(Graphics2D g, Font font, String value, float x, float y) {
    AttributedString str = new AttributedString(value);
    str.addAttribute(TextAttribute.FOREGROUND, Color.BLACK);
    str.addAttribute(TextAttribute.FONT, font);
    FontRenderContext frc = new FontRenderContext(null, true, true);
    TextLayout layout = new LineBreakMeasurer(str.getIterator(), frc).nextLayout(Integer.MAX_VALUE);
    layout.draw(g, x, y);
}
 
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: GlyphVectorOutline.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
private static void drawString(Graphics2D g, Font font, String value, float x, float y) {
    AttributedString str = new AttributedString(value);
    str.addAttribute(TextAttribute.FOREGROUND, Color.BLACK);
    str.addAttribute(TextAttribute.FONT, font);
    FontRenderContext frc = new FontRenderContext(null, true, true);
    TextLayout layout = new LineBreakMeasurer(str.getIterator(), frc).nextLayout(Integer.MAX_VALUE);
    layout.draw(g, x, y);
}
 
Example #13
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 #14
Source File: TestLineBreakWithFontSub.java    From jdk8u_jdk 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 #15
Source File: TextBoxPaintable.java    From pumpernickel with MIT License 5 votes vote down vote up
public TextBoxPaintable(String string, Font font, float maxWidth,
		float insets, Paint paint) {
	if (paint == null)
		paint = SystemColor.textText;
	this.insets = insets;
	this.text = string;
	this.paint = paint;

	List<String> lines = new ArrayList<String>();
	Map<TextAttribute, Object> attributes = new HashMap<TextAttribute, Object>();
	attributes.put(TextAttribute.FONT, font);
	AttributedString attrString = new AttributedString(string, attributes);
	LineBreakMeasurer lbm = new LineBreakMeasurer(attrString.getIterator(),
			frc);
	TextLayout tl = lbm.nextLayout(maxWidth);
	float dy = 0;
	GeneralPath path = new GeneralPath();
	int startIndex = 0;
	while (tl != null) {
		path.append(
				tl.getOutline(AffineTransform.getTranslateInstance(0, dy)),
				false);
		dy += tl.getAscent() + tl.getDescent() + tl.getLeading();
		int charCount = tl.getCharacterCount();
		lines.add(text.substring(startIndex, startIndex + charCount));
		startIndex += charCount;
		tl = lbm.nextLayout(maxWidth);
	}
	this.lines = lines.toArray(new String[lines.size()]);
	untransformedShape = path;
	Rectangle2D b = ShapeBounds.getBounds(untransformedShape);
	b.setFrame(b.getX(), b.getY(), b.getWidth() + 2 * insets, b.getHeight()
			+ 2 * insets);
	untransformedBounds = b.getBounds();
}
 
Example #16
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 #17
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 #18
Source File: ComplexTextLineWrapper.java    From jasperreports with GNU Lesser General Public License v3.0 5 votes vote down vote up
protected void startParagraph(AttributedCharacterIterator paragraph, boolean truncateAtChar)
{
	this.paragraph = paragraph;
	BreakIterator breakIt = truncateAtChar ? BreakIterator.getCharacterInstance() 
			: BreakIterator.getLineInstance();
	lineMeasurer = new LineBreakMeasurer(paragraph, breakIt, context.getFontRenderContext());
}
 
Example #19
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 * Integer.parseInt(element.getAttribute("size")))));
     
     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 #20
Source File: GlyphVectorOutline.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private static void drawString(Graphics2D g, Font font, String value, float x, float y) {
    AttributedString str = new AttributedString(value);
    str.addAttribute(TextAttribute.FOREGROUND, Color.BLACK);
    str.addAttribute(TextAttribute.FONT, font);
    FontRenderContext frc = new FontRenderContext(null, true, true);
    TextLayout layout = new LineBreakMeasurer(str.getIterator(), frc).nextLayout(Integer.MAX_VALUE);
    layout.draw(g, x, y);
}
 
Example #21
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 #22
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 #23
Source File: GlyphVectorOutline.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
private static void drawString(Graphics2D g, Font font, String value, float x, float y) {
    AttributedString str = new AttributedString(value);
    str.addAttribute(TextAttribute.FOREGROUND, Color.BLACK);
    str.addAttribute(TextAttribute.FONT, font);
    FontRenderContext frc = new FontRenderContext(null, true, true);
    TextLayout layout = new LineBreakMeasurer(str.getIterator(), frc).nextLayout(Integer.MAX_VALUE);
    layout.draw(g, x, y);
}
 
Example #24
Source File: GlyphVectorOutline.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
private static void drawString(Graphics2D g, Font font, String value, float x, float y) {
    AttributedString str = new AttributedString(value);
    str.addAttribute(TextAttribute.FOREGROUND, Color.BLACK);
    str.addAttribute(TextAttribute.FONT, font);
    FontRenderContext frc = new FontRenderContext(null, true, true);
    TextLayout layout = new LineBreakMeasurer(str.getIterator(), frc).nextLayout(Integer.MAX_VALUE);
    layout.draw(g, x, y);
}
 
Example #25
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 #26
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 #27
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 #28
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 #29
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 #30
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();
    }

}