Draws the given String on the given Graphics2D aligned to the top left and line wrapped inside of the the bounding rectangle. - Java 2D Graphics

Java examples for 2D Graphics:Text

Description

Draws the given String on the given Graphics2D aligned to the top left and line wrapped inside of the the bounding rectangle.

Demo Code


//package com.java2s;
import java.awt.Graphics2D;

import java.awt.font.FontRenderContext;
import java.awt.font.LineBreakMeasurer;
import java.awt.font.TextLayout;
import java.awt.font.TextAttribute;
import java.text.AttributedString;
import java.text.AttributedCharacterIterator;

public class Main {
    /**   Draws the given String on the given Graphics2D aligned to the top left and line wrapped inside of the the bounding rectangle.
       @param g The Graphics2D object on which to draw the string
       @param s The String to draw/*from www.j  av a2  s . c om*/
       @param x The minimum x coordinate of the rectangle in which to draw the string
       @param y The minimum y coordinate of the rectangle in which to draw the string
       @param width The width of the rectangle in which to draw the string
       @param height The height the rectangle in which to draw the string
     */
    // straight off the internet
    public static void drawWrappedString(Graphics2D g, String s, int x,
            int y, int width, int height) {
        if (s.length() == 0)
            return;

        AttributedString as = new AttributedString(s);
        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);
        int maxy = y + height;

        while (lbm.getPosition() < s.length()) {
            TextLayout tl = lbm.nextLayout(width);
            y += tl.getAscent();
            if (y > maxy)
                break;

            tl.draw(g, x, y);
            y += tl.getDescent() + tl.getLeading();
        }
    }
}

Related Tutorials