Java Graphics Draw Multiline String paintMultilineText(Graphics2D g2d, String text, int textX, int textWidth, int textY, int maxTextLineCount)

Here you can find the source of paintMultilineText(Graphics2D g2d, String text, int textX, int textWidth, int textY, int maxTextLineCount)

Description

paint Multiline Text

License

Open Source License

Declaration

public static int paintMultilineText(Graphics2D g2d, String text,
            int textX, int textWidth, int textY, int maxTextLineCount) 

Method Source Code

//package com.java2s;

import java.awt.Graphics2D;

import java.awt.font.FontRenderContext;
import java.awt.font.LineBreakMeasurer;

import java.awt.font.TextAttribute;
import java.awt.font.TextLayout;
import java.awt.geom.AffineTransform;

import java.text.AttributedString;

public class Main {
    public static int paintMultilineText(Graphics2D g2d, String text,
            int textX, int textWidth, int textY, int maxTextLineCount) {
        FontRenderContext frc = new FontRenderContext(
                new AffineTransform(), true, false);
        int fa = g2d.getFontMetrics().getAscent();

        if (text.length() == 0)
            return textY;

        int currOffset = 0;
        AttributedString attributedDescription = new AttributedString(text);
        attributedDescription.addAttribute(TextAttribute.FONT,
                g2d.getFont());/*from  w  w w  .  jav a 2  s.co m*/
        LineBreakMeasurer lineBreakMeasurer = new LineBreakMeasurer(
                attributedDescription.getIterator(), frc);
        int lineCount = 0;
        while (true) {
            TextLayout tl = lineBreakMeasurer.nextLayout(textWidth);
            if (tl == null)
                break;

            int charCount = tl.getCharacterCount();
            String line = text
                    .substring(currOffset, currOffset + charCount);

            g2d.drawString(line, textX, textY);

            textY += fa;
            currOffset += charCount;

            lineCount++;
            if ((maxTextLineCount > 0) && (lineCount == maxTextLineCount))
                break;
        }

        // textY += fh;

        return textY;
    }
}

Related

  1. drawString(Graphics g, String s, int x, int y)
  2. drawStringBiggest(final Graphics2D g2d, final Dimension dim, final String drawString)
  3. drawStringUnderlineCharAt(Graphics g, String s, int underlinedIndex, int x, int y)
  4. drawStyleString(final Graphics graphics, final String message, final int x, final int y, final Color color, final Color color1)
  5. drawTrimmedString(Graphics g, String s, int x, int y, int width)