Renders a ToggleButton and returns it as a BufferedImage. - Java 2D Graphics

Java examples for 2D Graphics:BufferedImage

Description

Renders a ToggleButton and returns it as a BufferedImage.

Demo Code

/**/*from w  w w  .jav a2  s  .c  om*/
 * 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 {
    /**
     * The standard font to use
     */
    public static final String FONT_NAME = "Lucida Sans";

    /**
     * Renders a ToggleButton and returns it as a BufferedImage. ToggleButton
     * does not wrap unless indicated to do so w/ \n. Also if two names are used
     * the second name appears at an offset. And since this is a togglebutton a
     * box and possible check mark in the box are added
     * @param text is the text of the togglebutton
     * @param text2 is the second text of the toggle button - added on a
     *            secondline and indented
     * @param party is the party of the candidate in the toggle button - right
     *            aligned on first line of button
     * @param fontsize the size of the font
     * @param wrappingWidth is not used
     * @param bold whether the button is bold
     * @param selected is whether or not the toggleButton should have a check
     *            mark in its box
     * @return the rendered ToggleButton
     */
    public static BufferedImage renderToggleButton(String text,
            String text2, String party, int fontsize, int wrappingWidth,
            boolean bold, boolean selected) {

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

        String box = "\u25a1"; // box character
        String check = "\u2713"; // check character

        BufferedImage wrappedImage = new BufferedImage(1000, 1000,
                BufferedImage.TYPE_INT_ARGB);

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

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

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

        int padding = 10;
        int heightPos = padding + baseline;
        int writePos = padding;

        int lineWidth = padding;

        int maxWidth = 0; // the max width of any line
        graphs.drawString(box + " " + text, writePos, heightPos);
        if (selected) {
            Font checkFont = new Font(FONT_NAME, Font.PLAIN,
                    (int) (fontsize - 4 + ((fontsize - 4) * 1.1)));
            graphs.setColor(new Color(0, 165, 80));
            graphs.setFont(checkFont);
            graphs.drawString(check, writePos, heightPos);
            graphs.setFont(font);
            graphs.setColor(Color.BLACK);
        }
        if (!party.equals("")) {
            int partyLength = lineWidth(party.split(" "), font);
            int partyPos = wrappingWidth - padding - partyLength;
            graphs.drawString(party, partyPos, heightPos);
        }

        if (!text2.equals("")) {
            heightPos += lineHeight(text, font);
            graphs.drawString("        " + text2, writePos, heightPos);
        }

        maxWidth = Math.max(lineWidth, maxWidth);

        graphs.setColor(Color.BLACK);
        graphs.setStroke(new BasicStroke(padding / 2));
        // start this rectangle off the top of our visible area so we don't see
        // the top border
        graphs.drawRect(0, -padding, wrappingWidth - 1, heightPos + 2
                * padding - 1);

        wrappedImage = wrappedImage.getSubimage(0, 0, wrappingWidth,
                heightPos + padding);

        return copy(wrappedImage);
    }

    /**
     * Calculates the line width at a given font
     * @param line is the line
     * @param font is the font
     * @return the width
     */
    private static int lineWidth(String[] line, Font font) {
        int width = 0;
        for (String word : line) {
            Rectangle2D measurement = font
                    .getStringBounds(word + " ", new FontRenderContext(
                            new AffineTransform(), true, true));
            width += measurement.getWidth();
        }

        return width;
    }

    /**
     * Calculates the line height at a given font, by looking at the height of
     * the first word
     * @param line is the line
     * @param font is the font
     * @return the height
     */
    private static int lineHeight(String line, Font font) {
        Rectangle2D measurement = font.getStringBounds(line + " ",
                new FontRenderContext(new AffineTransform(), true, true));
        return (int) measurement.getHeight();

    }

    /**
     * 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