Draws a string onto a buffered image, then draws that image onto the provided Graphics context. - Java 2D Graphics

Java examples for 2D Graphics:BufferedImage

Description

Draws a string onto a buffered image, then draws that image onto the provided Graphics context.

Demo Code


//package com.java2s;

import java.awt.Graphics;

import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.awt.image.ImageObserver;

public class Main {
    /**/*ww w  .  j ava  2s .  c  om*/
     * Draws a string onto a buffered image, then draws that image onto the provided Graphics context.
     * 
     * This function was meant to get around an OSX-specific bug, but unfortunately FontMetrics is either
     * poorly documented or a very gutsy liar, and the long and short of it is that this is more trouble than it's worth.
     * 
     * Should really be deleted, but I'm still sort of hoping we can make this work.
     */
    public static void drawBufferedString(Graphics g, String text, int x,
            int y, ImageObserver obs) {
        Rectangle2D bounds = g.getFontMetrics(g.getFont()).getStringBounds(
                text, g);
        int totalWidth = (int) (bounds.getWidth());
        int totalHeight = (int) (bounds.getHeight());

        BufferedImage im = new BufferedImage(totalWidth, totalHeight,
                BufferedImage.TYPE_INT_ARGB);
        Graphics img = im.getGraphics();
        img.setColor(g.getColor());
        img.drawString(text, 0, totalHeight);

        g.drawImage(im, x, y - totalHeight, obs);
    }
}

Related Tutorials