Java Graphics Draw String drawCenteredChar(Graphics g, char[] chars, int x, int y, int w, int h)

Here you can find the source of drawCenteredChar(Graphics g, char[] chars, int x, int y, int w, int h)

Description

draw Centered Char

License

LGPL

Declaration

public static void drawCenteredChar(Graphics g, char[] chars, int x, int y, int w, int h) 

Method Source Code


//package com.java2s;
/*//from   w  ww  .j a  va  2  s .c om
 * Copyright (c) 2007-2012 The Broad Institute, Inc.
 * SOFTWARE COPYRIGHT NOTICE
 * This software and its documentation are the copyright of the Broad Institute, Inc. All rights are reserved.
 *
 * This software is supplied without any warranty or guaranteed support whatsoever. The Broad Institute is not responsible for its use, misuse, or functionality.
 *
 * This software is licensed under the terms of the GNU Lesser General Public License (LGPL),
 * Version 2.1 which is available at http://www.opensource.org/licenses/lgpl-2.1.php.
 */

import java.awt.*;

public class Main {
    public static void drawCenteredChar(Graphics g, char[] chars, int x, int y, int w, int h) {

        // Get measures needed to center the message
        FontMetrics fm = g.getFontMetrics();

        // How many pixels wide is the string
        int msg_width = fm.charsWidth(chars, 0, 1);

        // How far above the baseline can the font go?
        int ascent = fm.getMaxAscent();

        // How far below the baseline?
        int descent = fm.getMaxDescent();

        // Use the string width to find the starting point
        int msgX = x + w / 2 - msg_width / 2;

        // Use the vertical height of this font to find
        // the vertical starting coordinate
        int msgY = y + h / 2 - descent / 2 + ascent / 2;

        g.drawChars(chars, 0, 1, msgX, msgY);

    }
}

Related

  1. centerString(Graphics g, String s, Font f, int w0, int w, int h)
  2. centerStringX(String s, int w, Graphics2D g2d)
  3. centerStringY(String s, int h, Graphics2D g2d)
  4. drawCentered(Graphics g, String text, Point p)
  5. drawCenteredString(Graphics g, Rectangle rect, String str)
  6. drawCenteredString(Graphics g, String str, int x, int y)
  7. drawCenteredString(String s, Graphics g, int x, int y)
  8. drawCenteredText(Graphics2D g, String text, int x, int y, float align_x, float align_y, float font_size)