Java Draw String drawString(Image img, String text, Color color)

Here you can find the source of drawString(Image img, String text, Color color)

Description

Dibuja un texto en el centro de la imagen, con el color indicado.

License

Open Source License

Declaration

public static Image drawString(Image img, String text, Color color) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;

public class Main {
    /**//  ww  w.  ja v  a2 s .  c o  m
     * Dibuja un texto en el centro de la imagen, con el color indicado. Retorna
     * una imagen nueva con los cambios, la imagen original no se modifica.
     */
    public static Image drawString(Image img, String text, Color color) {
        BufferedImage result = new BufferedImage(img.getWidth(null), img.getHeight(null),
                BufferedImage.TYPE_INT_ARGB);
        Graphics2D g = (Graphics2D) result.getGraphics();
        g.drawImage(img, 0, 0, null);

        Font font = new Font(Font.SANS_SERIF, Font.BOLD, 12);
        Rectangle2D r = font.getStringBounds(text, g.getFontRenderContext());
        g.setFont(font);

        g.setColor(color);
        g.drawString(text, img.getWidth(null) / 2 - (int) r.getWidth() / 2,
                img.getHeight(null) / 2 + (int) r.getHeight() / 2 - 2);
        return result;
    }
}

Related

  1. drawString(Graphics2D g, String string, int x, int y)
  2. drawString(Graphics2D g, String string, int x, int y, boolean includeOutline)
  3. drawString(Graphics2D g2, String str, int x, int y, int halign, int valign)
  4. drawString(Graphics2D gfx, String text, int x, int y)
  5. drawString(Graphics2D graphics, String text, double x, double y, boolean centerHorizontal, boolean centerVertical, Color backgroundColor)
  6. drawString(String pString, Graphics2D pG, int pX, int pY, int pWidth, int pHeight, boolean pYOverflow, boolean pShrinkWords, String pJustification, boolean pDraw)
  7. drawString(String txt, int x, int y, Graphics g)
  8. drawStringAlignCenter(Graphics2D g2d, String s, int x, int y)
  9. drawStringAt(Graphics g, String t, int x, int y, int where)