Draw a given String to a Graphics2D object - Java 2D Graphics

Java examples for 2D Graphics:Text

Introduction

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

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 {
    /**/*from   w w w. ja v a 2 s . co  m*/
     * Draw a given String to a graphic object
     *
     * @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
     * @param x
     * @param xpercent
     * @param y
     * @param ypercent
     */
    public static void drawStringAtPos(final Graphics2D g2d,
            final Dimension dim, final String drawString,
            final int fontSize, final double x, final boolean xpercent,
            final double y, final boolean ypercent) {
        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();

        double xfactor = 1;
        if (xpercent) {
            xfactor = dim.getWidth() / 100.0;
        }
        double yfactor = 1;
        if (ypercent) {
            yfactor = dim.getHeight() / 100.0;
        }

        posx = (float) (x * xfactor - bounds.getCenterX());
        posy = (float) (y * yfactor - 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