Java Graphics Draw String drawTextInBoundedArea(Graphics2D g2d, int x1, int y1, int x2, int y2, String text)

Here you can find the source of drawTextInBoundedArea(Graphics2D g2d, int x1, int y1, int x2, int y2, String text)

Description

draw Text In Bounded Area

License

Apache License

Declaration

private static void drawTextInBoundedArea(Graphics2D g2d, int x1,
            int y1, int x2, int y2, String text) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

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.text.AttributedCharacterIterator;
import java.text.AttributedString;

public class Main {
    private static void drawTextInBoundedArea(Graphics2D g2d, int x1,
            int y1, int x2, int y2, String text) {
        float interline = 1;
        float width = x2 - x1;
        AttributedString as = new AttributedString(text);
        as.addAttribute(TextAttribute.FOREGROUND, g2d.getPaint());
        as.addAttribute(TextAttribute.FONT, g2d.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(width);
            y1 += tl.getAscent();//from w ww. j  a  va  2s . co m
            tl.draw(g2d, x1, y1);
            y1 += tl.getDescent() + tl.getLeading() + (interline - 1.0f)
                    * tl.getAscent();
            if (y1 > y2) {
                break;
            }
        }
    }
}

Related

  1. drawScaleLabel(Graphics g, String label, int x, int y, boolean yAxisP)
  2. drawSystemNameLabel(Graphics2D g, String sysName, Color color, double safetyOffset, boolean isLocationKnownUpToDate)
  3. drawText(Graphics graphics, int x, int y, String text)
  4. drawText(Graphics2D graphics, Font font, Dimension2D dimension, String text)
  5. drawTextCenter(Graphics2D g2, String str, int x, int y)
  6. drawTuplet(Graphics g, int x, int y, int x2, int y2, int bi, String s1, String s2)
  7. drawUnderlineCharAt(Graphics g, String text, int underlinedIndex, int x, int y)
  8. drawVerticalText(Graphics2D graphics, Font font, Dimension2D dimension, String text)
  9. drawVerticalTextCenter(Graphics2D g2, String str, int x, int y)