Draw a given String to a graphic object centered - Java 2D Graphics

Java examples for 2D Graphics:Text

Introduction

The following code shows how to Draw a given String to a graphic object centered .

Demo Code

//package com.java2s;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.font.FontRenderContext;
import java.awt.font.TextLayout;
import java.awt.geom.Rectangle2D;

public class Main {
    /**//  www. j a va  2 s . co m
     * Draw a given String to a graphic object centered
     *
     * @param g2d the graphics to draw to
     * @param dim the dimension to stay into
     * @param drawString the string to draw
     * @param fontSize chosen FontSize to draw with
     */
    public static void drawStringCentered(final Graphics2D g2d,
            final Dimension dim, final String drawString, final int fontSize) {
        Rectangle2D bounds;

        Object KEY_ANTIALIASING_before = g2d
                .getRenderingHint(RenderingHints.KEY_ANTIALIASING);
        Object KEY_TEXT_ANTIALIASING_before = g2d
                .getRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING);

        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_OFF);
        g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
                RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);

        float posx = 0, posy = 0;

        g2d.setFont(g2d.getFont().deriveFont(Font.PLAIN, fontSize));
        FontRenderContext frc = g2d.getFontRenderContext();
        TextLayout tl = new TextLayout(drawString, g2d.getFont(), frc);
        bounds = tl.getBounds();
        posx = (float) (dim.getWidth() / 2 - bounds.getCenterX());
        posy = (float) (dim.getHeight() / 2 - bounds.getCenterY());

        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                KEY_ANTIALIASING_before);
        g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
                KEY_TEXT_ANTIALIASING_before);

        g2d.drawString(drawString, (int) posx, (int) posy);
    }
}

Related Tutorials