Draw a text in the center of the bounds. - Java 2D Graphics

Java examples for 2D Graphics:Text

Description

Draw a text in the center of the bounds.

Demo Code


//package com.java2s;

import java.awt.FontMetrics;

import java.awt.Graphics2D;

import java.awt.Rectangle;
import java.awt.font.TextLayout;

import java.awt.geom.Rectangle2D;

public class Main {
    /**//from   w ww .  j  av a2s.  c  om
     * Draw a text in the center of the bounds.
     */
    public static void drawString(String text, Rectangle bounds,
            Graphics2D g2) {
        FontMetrics metrics = g2.getFontMetrics();
        Rectangle2D textBounds = metrics.getStringBounds(text, g2);
        int x = (int) (bounds.x + bounds.width / 2 - textBounds.getWidth() / 2);
        int y = (int) (bounds.y + bounds.height / 2 - textBounds
                .getHeight() / 2);
        y += metrics.getAscent();
        g2.drawString(text, x, y);
    }

    public static void drawString(String text, int boundsX, int boundsY,
            int boundsWidth, int boundsHeight, Graphics2D g2) {
        FontMetrics metrics = g2.getFontMetrics();
        Rectangle2D textBounds = metrics.getStringBounds(text, g2);
        int x = (int) (boundsX + boundsWidth / 2 - textBounds.getWidth() / 2);
        int y = (int) (boundsY + boundsHeight / 2 - textBounds.getHeight() / 2);
        y += metrics.getAscent();
        g2.drawString(text, x, y);
    }

    public static void drawString(java.util.List textLayouts,
            Rectangle bounds, int buffer, Graphics2D g2) {
        float w = (float) bounds.getWidth();
        TextLayout layout = (TextLayout) textLayouts.get(0);
        float x = (float) (w - layout.getAdvance()) / 2 + bounds.x;
        float y = (float) (layout.getAscent() + buffer) + bounds.y;
        layout.draw(g2, x, y);
        y += (layout.getDescent() + layout.getLeading());
        for (int i = 1; i < textLayouts.size(); i++) {
            layout = (TextLayout) textLayouts.get(i);
            x = (float) (w - layout.getAdvance()) / 2 + bounds.x;
            y += layout.getAscent();
            layout.draw(g2, x, y);
            y += (layout.getDescent() + layout.getLeading());
        }
    }
}

Related Tutorials