draw String Centered At - Java 2D Graphics

Java examples for 2D Graphics:Text

Description

draw String Centered At

Demo Code


import java.awt.Component;
import java.awt.Dimension;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Insets;
import java.awt.Polygon;
import java.awt.font.FontRenderContext;
import java.awt.font.LineBreakMeasurer;
import java.awt.font.TextAttribute;
import java.awt.font.TextLayout;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.ImageObserver;
import java.text.AttributedCharacterIterator;
import java.text.AttributedString;
import javax.swing.plaf.basic.BasicGraphicsUtils;

public class Main{
    public static final double density = getDisplayDensity();
    public static final double scale = getScale();
    public static void drawStringCenteredAt(Graphics g, String text, int x,
            int y) {
        drawStringCenteredAt(g, text, '\0', x, y);
    }//  w ww. j  a  va 2s . c o m
    public static void drawStringCenteredAt(Graphics g, String text,
            char ch, int x, int y) {
        FontMetrics metrics = g.getFontMetrics(g.getFont());
        BasicGraphicsUtils.drawString(g, text, ch, GraphicsUtil.scale(x)
                - metrics.stringWidth(text) / 2, GraphicsUtil.scale(y));
    }
    public static void drawStringCenteredAt(Graphics g, String text,
            int centerX, int startY, int wrapWidth) {
        AttributedString as = new AttributedString(text);
        as.addAttribute(TextAttribute.FONT, g.getFont());

        AttributedCharacterIterator aci = as.getIterator();
        FontRenderContext frc = ((Graphics2D) g).getFontRenderContext();

        LineBreakMeasurer lbm = new LineBreakMeasurer(aci, frc);

        int x = scale(centerX);
        int y = scale(startY);
        int width = scale(wrapWidth);

        lbm.setPosition(0);

        TextLayout tl;
        while (lbm.getPosition() < text.length()) {
            tl = lbm.nextLayout(width);
            tl.draw((Graphics2D) g,
                    (float) (x - tl.getBounds().getWidth() / 2),
                    y += tl.getAscent());
            y += tl.getDescent() + tl.getLeading();
        }
    }
    public static void drawString(Graphics g, String string, int x, int y) {
        g.drawString(string, scale(x), scale(y));
    }
    public static int scale(int i) {
        return (int) (i * density / scale);
    }
}

Related Tutorials