paint Drop Shadowed Text - Java 2D Graphics

Java examples for 2D Graphics:Text

Description

paint Drop Shadowed Text

Demo Code


//package com.java2s;
import java.awt.*;

import java.awt.image.BufferedImage;
import java.awt.image.ConvolveOp;
import java.awt.image.Kernel;

public class Main {
    /**//from w ww . j  a  v a2s .c o m
     *
     * @param g Graphics that will paint text
     * @param text String to be written
     * @param kernelSize Size of the Kernel
     * @param blurFactor Amount of Blur
     * @param shadowColor Color of the shadow
     * @param shiftX Coords x shift factor
     * @param shiftY Coords y shift factor
     */
    public static void paintDropShadowedText(Graphics g, String text,
            int kernelSize, float blurFactor, Color shadowColor,
            int shiftX, int shiftY) {
        Color startColor = g.getColor();

        float[] kernelData = new float[kernelSize * kernelSize];
        for (int i = 0; i < kernelData.length; i++) {
            kernelData[i] = blurFactor;
        }
        int padding = 10;
        ConvolveOp blur = new ConvolveOp(new Kernel(kernelSize, kernelSize,
                kernelData));
        FontMetrics fm = g.getFontMetrics();
        int textWidth = fm.stringWidth(text);
        int textHeight = fm.getAscent() + fm.getDescent();
        int imageWidth = textWidth + padding;
        int imageHeight = textHeight + padding;

        BufferedImage textImage = new BufferedImage(imageWidth,
                imageHeight, 2);
        BufferedImage dropShadowImage = new BufferedImage(imageWidth,
                imageHeight, 2);

        Graphics2D textImageG = textImage.createGraphics();
        textImageG.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);
        textImageG.setFont(g.getFont());
        textImageG.setColor(shadowColor);
        paintText(textImageG, text, imageWidth, imageHeight);
        textImageG.dispose();

        Graphics2D blurryImageG = dropShadowImage.createGraphics();
        blurryImageG.drawImage(textImage, blur, shiftX, shiftY);
        blurryImageG.setColor(startColor);
        blurryImageG.setFont(g.getFont());

        blurryImageG.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);
        paintText(blurryImageG, text, imageWidth, imageHeight);
        blurryImageG.dispose();

        g.drawImage(dropShadowImage, 0, 0, null);
    }

    /**
     *
     * @param g Graphics that paint text
     * @param text String to be painted
     * @param w Width of string
     * @param h Height of string
     */
    public static void paintText(Graphics g, String text, int w, int h) {
        FontMetrics fm = g.getFontMetrics();
        int stringWidth = fm.stringWidth(text);
        g.drawString(text, (w - stringWidth) / 2,
                (h - fm.getAscent() - fm.getDescent()) / 2 + fm.getAscent());
    }
}

Related Tutorials