Renders a Button and returns it as a BufferedImage. Buttons do not automatically wrap - must be wrapped w/ a \n in the text of the button - Java 2D Graphics

Java examples for 2D Graphics:BufferedImage

Description

Renders a Button and returns it as a BufferedImage. Buttons do not automatically wrap - must be wrapped w/ a \n in the text of the button

Demo Code

/**/*from   w  ww  .j  a  v a 2  s  .  c o  m*/
 * This file is part of VoteBox.
 * 
 * VoteBox is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as published by
 * the Free Software Foundation.
 * 
 * You should have received a copy of the GNU General Public License
 * along with VoteBox, found in the root of any distribution or
 * repository containing all or part of VoteBox.
 * 
 * THIS SOFTWARE IS PROVIDED BY WILLIAM MARSH RICE UNIVERSITY, HOUSTON,
 * TX AND IS PROVIDED 'AS IS' AND WITHOUT ANY EXPRESS, IMPLIED OR
 * STATUTORY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, WARRANTIES OF
 * ACCURACY, COMPLETENESS, AND NONINFRINGEMENT.  THE SOFTWARE USER SHALL
 * INDEMNIFY, DEFEND AND HOLD HARMLESS RICE UNIVERSITY AND ITS FACULTY,
 * STAFF AND STUDENTS FROM ANY AND ALL CLAIMS, ACTIONS, DAMAGES, LOSSES,
 * LIABILITIES, COSTS AND EXPENSES, INCLUDING ATTORNEYS' FEES AND COURT
 * COSTS, DIRECTLY OR INDIRECTLY ARISING OUR OF OR IN CONNECTION WITH
 * ACCESS OR USE OF THE SOFTWARE.
 */
//package com.java2s;
import java.awt.BasicStroke;
import java.awt.Color;

import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.font.FontRenderContext;
import java.awt.geom.AffineTransform;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;

public class Main {
    /**
     * Max dimensions for buttons. Longer text will be clipped.
     */
    public static final int MAX_BUTTON_WIDTH = 600;
    public static final int MAX_BUTTON_HEIGHT = 100;
    /**
     * The standard font to use
     */
    public static final String FONT_NAME = "Lucida Sans";

    /**
     * Renders a Button and returns it as a BufferedImage.<br>
     * Buttons do not automatically wrap - must be wrapped w/ a \n in the text
     * of the button
     * @param text is the text of the button
     * @param fontsize is the size of the font
     * @param bold is whether the button is bold
     * @param boxed whether the button is boxed
     * @param backGroundColor is the background color of the button
     * @param preferredWidth desired width of the button, honored if possible
     * @return the rendered Button
     */
    public static BufferedImage renderButton(String text, int fontsize,
            boolean bold, boolean boxed, int preferredWidth,
            Color backGroundColor) {

        Font font = new Font(FONT_NAME, (bold) ? Font.BOLD : Font.PLAIN,
                fontsize);

        BufferedImage wrappedImage = new BufferedImage(MAX_BUTTON_WIDTH,
                MAX_BUTTON_HEIGHT, BufferedImage.TYPE_INT_RGB);

        Graphics2D graphs = wrappedImage.createGraphics();
        graphs.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);
        graphs.setFont(font);

        graphs.setPaint(backGroundColor);
        graphs.fillRect(0, 0, MAX_BUTTON_WIDTH, MAX_BUTTON_HEIGHT);

        graphs.setColor(Color.BLACK); // Could make this a variable

        int baseline = graphs.getFontMetrics().getAscent();

        String[] words = text.split(" ");
        int padding = 10;
        int leading = 1;
        int heightPos = padding + baseline;
        int writePos = padding;

        int lineWidth = padding;

        int maxWidth = 0; // the max width of any line
        for (String word : words) // For each word try placing it on the line,
        // if not jump down a line and then write it
        {
            Rectangle2D measurement = font
                    .getStringBounds(word + " ", new FontRenderContext(
                            new AffineTransform(), true, true));
            int wordWidth = (int) measurement.getWidth();
            writePos = lineWidth;
            lineWidth += wordWidth;

            if (word.equals("\n")) {
                maxWidth = Math.max(lineWidth, maxWidth);
                heightPos += baseline + leading;
                writePos = padding;
                lineWidth = padding;
            }
            graphs.drawString(word + " ", writePos, heightPos);
        }
        maxWidth = Math.max(lineWidth, maxWidth);

        if (preferredWidth > 0)
            maxWidth = preferredWidth;

        if (boxed) {
            graphs.setColor(Color.BLACK);
            graphs.setStroke(new BasicStroke(padding / 2));
            graphs.drawRect(0, 0, maxWidth - 1, heightPos + padding - 1);
        }

        // Cut the image down to the correct size
        wrappedImage = wrappedImage.getSubimage(0, 0, maxWidth, heightPos
                + padding);

        return copy(wrappedImage);

    }

    /**
     * Copies a buffered Image. Borrowed 100% from
     * http://cui.unige.ch/~deriazm/javasources/ImgTools.java I really can't
     * think of a better way of writing this code - so i just used theirs
     */
    public static BufferedImage copy(BufferedImage bImage) {
        int w = bImage.getWidth(null);
        int h = bImage.getHeight(null);
        BufferedImage bImage2 = new BufferedImage(w, h,
                BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2 = bImage2.createGraphics();
        g2.drawImage(bImage, 0, 0, null);
        return bImage2;
    }
}

Related Tutorials