Java Graphics Draw String paintCenteredString(Graphics2D g, String str, Font font, int centerX, int centerY)

Here you can find the source of paintCenteredString(Graphics2D g, String str, Font font, int centerX, int centerY)

Description

Paint a String centered at a given (x,y) coordinate.

License

Open Source License

Declaration

public static void paintCenteredString(Graphics2D g, String str, Font font, int centerX, int centerY) 

Method Source Code

//package com.java2s;
/**//from  w  w w.ja  v a  2 s  .  c o  m
 * This software is released as part of the Pumpernickel project.
 * 
 * All com.pump resources in the Pumpernickel project are distributed under the
 * MIT License:
 * https://raw.githubusercontent.com/mickleness/pumpernickel/master/License.txt
 * 
 * More information about the Pumpernickel project is available here:
 * https://mickleness.github.io/pumpernickel/
 */

import java.awt.Font;
import java.awt.FontMetrics;

import java.awt.Graphics2D;

import java.awt.geom.Rectangle2D;

public class Main {
    /**
     * Paint a String centered at a given (x,y) coordinate.
     */
    public static void paintCenteredString(Graphics2D g, String str, Font font, int centerX, int centerY) {
        g.setFont(font);
        FontMetrics fm = g.getFontMetrics();
        Rectangle2D r = fm.getStringBounds(str, g);
        float x = (float) (centerX - r.getWidth() / 2);
        float y = (float) (centerY - r.getHeight() / 2 - r.getY());
        g.drawString(str, x, y);
    }
}

Related

  1. drawTuplet(Graphics g, int x, int y, int x2, int y2, int bi, String s1, String s2)
  2. drawUnderlineCharAt(Graphics g, String text, int underlinedIndex, int x, int y)
  3. drawVerticalText(Graphics2D graphics, Font font, Dimension2D dimension, String text)
  4. drawVerticalTextCenter(Graphics2D g2, String str, int x, int y)
  5. drawWrappedText(Graphics2D g2, float x, float y, float width, String text)
  6. paintOutline(Graphics g, String s, int textX, int textY, int thickness)
  7. paintShadowTitleFat(Graphics g, String title, int x, int y, Color frente, Color shadow, int desp)
  8. paintTextEffect(final Graphics2D g2d, final String s, final Color c, final int size, final double tx, final double ty, final boolean isShadow)
  9. paintTexture(BufferedImage pattern, BufferedImage template)