Java Draw Centered drawStringCentered(Graphics graphics, String string, Rectangle area)

Here you can find the source of drawStringCentered(Graphics graphics, String string, Rectangle area)

Description

draw String Centered

License

Open Source License

Declaration

public static void drawStringCentered(Graphics graphics, String string, Rectangle area) 

Method Source Code

//package com.java2s;
/*//from w ww .j av a2 s.  com
 *  File: GraphicsHelper.java 
 *  Copyright (c) 2004-2007  Peter Kliem (Peter.Kliem@jaret.de)
 *  A commercial license is available, see http://www.jaret.de.
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Common Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/cpl-v10.html
 */

import java.awt.Graphics;

import java.awt.Rectangle;
import java.awt.geom.Rectangle2D;

public class Main {
    public static void drawStringCentered(Graphics graphics, String string, int left, int right, int y) {
        Rectangle2D rect = graphics.getFontMetrics().getStringBounds(string, graphics);
        int width = right - left;
        int xx = (int) ((width - rect.getWidth()) / 2);
        graphics.drawString(string, xx, y);

    }

    /**
     * @param graphics graphics to use
     * @param string string to render
     * @param x center x
     * @param y basey
     */
    public static void drawStringCentered(Graphics graphics, String string, int x, int y) {
        Rectangle2D rect = graphics.getFontMetrics().getStringBounds(string, graphics);
        int xx = x - (int) ((rect.getWidth()) / 2);
        graphics.drawString(string, xx, y);
    }

    public static void drawStringCentered(Graphics graphics, String string, Rectangle area) {
        Rectangle2D rect = graphics.getFontMetrics().getStringBounds(string, graphics);
        int xx = area.x + area.width / 2 - (int) ((rect.getWidth()) / 2);
        int yy = (int) (area.y + area.height / 2 + (rect.getHeight() / 2));
        graphics.drawString(string, xx, yy);
    }
}

Related

  1. drawEllipseOld(Graphics g, double xCenter, double yCenter, double semiMA, double semiMI, double angle)
  2. drawStringCenter(Graphics2D g, String text, Rectangle rect, int fontHeight, Color c)
  3. drawStringCenter(Object o, Rectangle r, Font f, Graphics2D g)
  4. drawStringCentered(final Graphics2D g2d, final Dimension dim, final String drawString, final int fontSize)
  5. drawStringCentered(Graphics g, String str, int x, int y, int width, int height)
  6. drawStringCentered(Graphics2D g, String text, int x, int y, int fontHeight, Color c)
  7. drawVerticallyCenteredText(String text, int margin, Rectangle rect, Graphics g2D, boolean rightJustify)