Java Draw Image drawInMiddle(Graphics g, Image image, String text)

Here you can find the source of drawInMiddle(Graphics g, Image image, String text)

Description

Draws the text in the center of the image.

License

Open Source License

Parameter

Parameter Description
g The graphics device
image Image to draw on
text Text to draw

Declaration

public static void drawInMiddle(Graphics g, Image image, String text) 

Method Source Code


//package com.java2s;
/*/*from  w  ww  .j a  va  2 s  . c  o  m*/
 * This file is part of Javaders.
 * Copyright (c) Yossi Shaul
 *
 * Javaders is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Javaders is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Javaders.  If not, see <http://www.gnu.org/licenses/>.
 */

import java.awt.*;

public class Main {
    /**
     * Draws the text in the center of the image.
     *
     * @param g     The graphics device
     * @param image Image to draw on
     * @param text  Text to draw
     */
    public static void drawInMiddle(Graphics g, Image image, String text) {

        int width = image.getWidth(null);
        int height = image.getHeight(null);

        FontMetrics fm = g.getFontMetrics();
        int midX = (width - fm.stringWidth(text)) / 2;
        int midY = (height + fm.getHeight() / 2) / 2;

        g.drawString(text, midX, midY);

    }
}

Related

  1. drawImageInOval(Graphics2D gr, Image img, Rectangle r, boolean noShrink)
  2. drawImageInPolygon(Graphics g2d, BufferedImage img, Polygon poly, double xfactor, double yfactor)
  3. drawImageInRect(Graphics g2d, BufferedImage img, Rectangle rect, double xfactor, double yfactor)
  4. drawImageInRect(Graphics2D gr, Image img, Rectangle r, boolean noShrink)
  5. drawImageWithClipping(Graphics g, BufferedImage img)
  6. drawLabel(BufferedImage image, String text)
  7. drawNormalImage(Rectangle2D bounds, Graphics2D g2, Image image, ImageObserver observer, int imageWidth, int imageHeight)
  8. drawOnto(final BufferedImage pDestination, final Image pSource)
  9. drawPixel(BufferedImage img, int x, int y, int color)