performs the annoying calculation required for centering text in a box of size d. - Java 2D Graphics

Java examples for 2D Graphics:Text

Description

performs the annoying calculation required for centering text in a box of size d.

Demo Code


//package com.java2s;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;

import java.awt.geom.Point2D;

public class Main {
    /** performs the annoying calculation required for centering text in a box of size d.
     * Try to reuse this result as calculating string bounds is not terribly efficient.
     * *//*w ww  .  j av  a  2  s. c om*/
    public static Point2D getCenteredText(Graphics g, Font f, Dimension d,
            String s) {
        // Find the size of string s in font f in the current Graphics context g.
        FontMetrics fm = g.getFontMetrics(f);
        java.awt.geom.Rectangle2D rect = fm.getStringBounds(s, g);

        // Center text horizontally and vertically
        double x = (d.getWidth() - rect.getWidth()) / 2;
        double y = (d.getHeight() - rect.getHeight()) / 2 + fm.getAscent();

        return new Point2D.Double(x, y);
    }
}

Related Tutorials