Example usage for java.awt.font FontRenderContext FontRenderContext

List of usage examples for java.awt.font FontRenderContext FontRenderContext

Introduction

In this page you can find the example usage for java.awt.font FontRenderContext FontRenderContext.

Prototype

public FontRenderContext(AffineTransform tx, Object aaHint, Object fmHint) 

Source Link

Document

Constructs a FontRenderContext object from an optional AffineTransform and two Object values that determine if the newly constructed object has anti-aliasing or fractional metrics.

Usage

From source file:TextBouncer.java

public TextBouncer(String s, Font f) {
    previousTimes = new long[128];
    previousTimes[0] = System.currentTimeMillis();
    previousIndex = 1;/*from www  . ja va  2s  .  c o  m*/
    previousFilled = false;

    mString = s;
    setFont(f);
    Random random = new Random();
    mX = random.nextFloat() * 500;
    mY = random.nextFloat() * 500;
    mDeltaX = random.nextFloat() * 3;
    mDeltaY = random.nextFloat() * 3;
    mShearX = random.nextFloat() / 2;
    mShearY = random.nextFloat() / 2;
    mShearDeltaX = mShearDeltaY = .05f;
    FontRenderContext frc = new FontRenderContext(null, true, false);
    Rectangle2D bounds = getFont().getStringBounds(mString, frc);
    mWidth = (float) bounds.getWidth();
    mHeight = (float) bounds.getHeight();
    // Make sure points are within range.
    addComponentListener(new ComponentAdapter() {
        public void componentResized(ComponentEvent ce) {
            Dimension d = getSize();
            if (mX < 0)
                mX = 0;
            else if (mX + mWidth >= d.width)
                mX = d.width - mWidth - 1;
            if (mY < 0)
                mY = 0;
            else if (mY + mHeight >= d.height)
                mY = d.height - mHeight - 1;
        }
    });
}

From source file:components.SizeDisplayer.java

private Dimension getTextSize(Graphics2D g2d) {
    if (text == null) {
        textSizeD.setSize(0, 0);/*w w w.  j  a  va2 s . c  om*/
    } else {
        FontRenderContext frc;
        if (g2d != null) {
            frc = g2d.getFontRenderContext();
        } else {
            frc = new FontRenderContext(null, false, false);
        }
        Rectangle2D textRect = getFont().getStringBounds(text, frc);
        textSizeR.setRect(textRect);
        textSizeD.setSize(textSizeR.width, textSizeR.height);
    }

    return textSizeD;
}

From source file:org.fhaes.fhrecorder.view.GraphSummaryOverlay.java

/**
 * @return the approximate width of the label in pixels corresponding to the largest value of the overlay graph's y axis.
 *///from   ww  w.  j ava2 s.  c o m
public int getMaximumRangeLabelWidth() {

    String maxRangeString = Integer.toString(maxRange);
    FontRenderContext frc = new FontRenderContext(new AffineTransform(), true, true);
    Font font = new Font("SansSerif", Font.PLAIN, 10);
    return (int) (font.getStringBounds(maxRangeString, frc).getWidth() + 6);
}

From source file:piramide.interaction.reasoner.FuzzyReasonerWizardFacade.java

private BufferedImage createErrorMessagesImage(String text) {
    final Font font = TextTitle.DEFAULT_FONT;
    final Font bigBold = new Font(font.getName(), Font.BOLD, 24);
    final FontRenderContext frc = new FontRenderContext(null, true, false);
    final TextLayout layout = new TextLayout(text, bigBold, frc);
    final Rectangle2D bounds = layout.getBounds();
    final int w = (int) Math.ceil(bounds.getWidth());
    final int h = (int) Math.ceil(bounds.getHeight());
    final BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
    final Graphics2D g = image.createGraphics();
    g.setColor(Color.WHITE);//from w w w  . j a  v a2  s  . c o m
    g.fillRect(0, 0, w, h);
    g.setColor(Color.RED);
    g.setFont(bigBold);
    g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
    g.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_OFF);
    g.drawString(text, (float) -bounds.getX(), (float) -bounds.getY());
    g.dispose();
    return image;
}

From source file:com.atlassian.theplugin.idea.bamboo.tree.BuildTreeNode.java

private void recalculateColumnWidths(final BuildListModel buildModel) {
    JLabel l = new JLabel();

    reasonWidth = 0.0;//from  ww w  .j  av a  2s .  c o m
    serverWidth = 0.0;
    dateWidth = 0.0;
    planInProgressWidth = 0.0;

    for (BambooBuildAdapter b : buildModel.getBuilds()) {
        // PL-1202 - argument to TextLayout must be a non-empty string
        String reason = getBuildReasonString(b);
        TextLayout layoutStatus = new TextLayout(reason.length() > 0 ? reason : ".", l.getFont(),
                new FontRenderContext(null, true, true));
        reasonWidth = Math.max(layoutStatus.getBounds().getWidth(), reasonWidth);
        String server = getBuildServerString(b);
        TextLayout layoutName = new TextLayout(server.length() > 0 ? server : ".", l.getFont(),
                new FontRenderContext(null, true, true));
        serverWidth = Math.max(layoutName.getBounds().getWidth(), serverWidth);
        String date = getRelativeBuildTimeString(b);
        TextLayout layoutDate = new TextLayout(date.length() > 0 ? date : ".", l.getFont(),
                new FontRenderContext(null, true, true));
        dateWidth = Math.max(layoutDate.getBounds().getWidth(), dateWidth);

        TextLayout planStatus = new TextLayout(
                build.getPlanStateString().length() > 0 ? build.getPlanStateString() : " ", l.getFont(),
                new FontRenderContext(null, true, true));
        planInProgressWidth = Math.max(planStatus.getBounds().getWidth(), planInProgressWidth);
    }
}

From source file:com.lfv.lanzius.server.WorkspaceView.java

@Override
protected void paintComponent(Graphics g) {
    int w = getWidth();
    int h = getHeight();

    Document doc = server.getDocument();

    Color storedCol = g.getColor();
    Font storedFont = g.getFont();

    // Fill workspace area
    g.setColor(getBackground());/*from ww  w .  j av  a  2  s  . c  om*/
    g.fillRect(0, 0, w, h);

    // Should the cached version be updated?
    int updateDocumentVersion = server.getDocumentVersion();
    boolean update = (documentVersion != updateDocumentVersion);

    // Check if we have cached the latest document version, otherwise cache the terminals
    if (update) {
        log.debug("Updating view to version " + updateDocumentVersion);
        terminalMap.clear();
        groupList.clear();
        if (doc != null) {
            synchronized (doc) {

                // Clear the visible attribute on all groups
                // except the started or paused ones
                Element egd = doc.getRootElement().getChild("GroupDefs");
                Iterator iter = egd.getChildren().iterator();
                while (iter.hasNext()) {
                    Element eg = (Element) iter.next();
                    boolean isVisible = !DomTools.getAttributeString(eg, "state", "stopped", false)
                            .equals("stopped");
                    eg.setAttribute("visible", String.valueOf(isVisible));
                }

                // Gather information about terminals and cache it
                Element etd = doc.getRootElement().getChild("TerminalDefs");
                iter = etd.getChildren().iterator();
                while (iter.hasNext()) {
                    Element et = (Element) iter.next();
                    int tid = DomTools.getAttributeInt(et, "id", 0, false);
                    if (tid > 0) {
                        // Create terminal and add it to list
                        Terminal t = new Terminal(tid, DomTools.getAttributeInt(et, "x", 0, false),
                                DomTools.getAttributeInt(et, "y", 0, false),
                                DomTools.getChildText(et, "Name", "T/" + tid, false),
                                DomTools.getAttributeBoolean(et, "online", false, false),
                                DomTools.getAttributeBoolean(et, "selected", false, false));
                        terminalMap.put(tid, t);

                        // Is the terminal monitored?
                        t.isMonitored = DomTools.getAttributeBoolean(et, "monitored", false, false);

                        // Examine the Player element under PlayerSetup
                        t.groupColor = null;
                        Element ep = DomTools.getElementFromSection(doc, "PlayerSetup", "terminalid",
                                String.valueOf(tid));

                        // Has linked player for this terminal
                        if (ep != null) {
                            StringBuffer sb = new StringBuffer();

                            // Append player name
                            sb.append(DomTools.getChildText(ep, "Name", "P/?", true));
                            sb.append(" (");

                            // Append role list
                            boolean hasRoles = false;
                            Element ers = ep.getChild("RoleSetup");
                            if (ers != null) {
                                Iterator iterr = ers.getChildren().iterator();

                                while (iterr.hasNext()) {
                                    Element er = (Element) iterr.next();
                                    String id = er.getAttributeValue("id");
                                    er = DomTools.getElementFromSection(doc, "RoleDefs", "id", id);
                                    if (er != null) {
                                        sb.append(DomTools.getChildText(er, "Name", "R/" + id, false));
                                        sb.append(", ");
                                        hasRoles = true;
                                    }
                                }
                                if (hasRoles) {
                                    // Trim last comma
                                    int len = sb.length();
                                    sb.setLength(Math.max(len - 2, 0));
                                }
                                sb.append(")");
                            }
                            t.roles = sb.toString();

                            // Is the player relocated?
                            t.isRelocated = DomTools.getAttributeBoolean(ep, "relocated", false, false);

                            // Get group name and color
                            Element eg = DomTools.getElementFromSection(doc, "GroupDefs", "id",
                                    DomTools.getAttributeString(ep, "groupid", "0", true));
                            t.groupColor = Color.lightGray;
                            if (eg != null) {
                                String sc = DomTools.getChildText(eg, "Color", null, false);
                                if (sc != null) {
                                    try {
                                        t.groupColor = Color.decode(sc);
                                    } catch (NumberFormatException ex) {
                                        log.warn("Invalid color attribute on Group node, defaulting to grey");
                                    }
                                }
                                //t.name += "  "+DomTools.getChildText(eg, "Name", "G/"+eg.getAttributeValue("id"), false);
                                t.groupName = DomTools.getChildText(eg, "Name",
                                        "G/" + eg.getAttributeValue("id"), false);

                                // This group should now be visible
                                eg.setAttribute("visible", "true");
                            } else
                                log.warn("Invalid groupid attribute on Player node, defaulting to grey");
                        }
                    } else
                        log.error("Invalid id attribute on Terminal node, skipping");
                }

                // Gather information about groups and cache it
                iter = egd.getChildren().iterator();
                while (iter.hasNext()) {
                    Element eg = (Element) iter.next();
                    if (DomTools.getAttributeBoolean(eg, "visible", false, false)) {
                        int gid = DomTools.getAttributeInt(eg, "id", 0, true);
                        if (gid > 0) {
                            Group grp = new Group(gid, DomTools.getChildText(eg, "Name", "G/" + gid, false),
                                    DomTools.getAttributeBoolean(eg, "selected", false, false));
                            groupList.add(grp);

                            // group color
                            String sc = DomTools.getChildText(eg, "Color", null, false);
                            if (sc != null) {
                                try {
                                    grp.color = Color.decode(sc);
                                } catch (NumberFormatException ex) {
                                    log.warn("Invalid color attribute on Group node, defaulting to grey");
                                }
                            }

                            // state color
                            grp.stateColor = Color.red;
                            String state = DomTools.getAttributeString(eg, "state", "stopped", false);
                            if (state.equals("started"))
                                grp.stateColor = Color.green;
                            else if (state.equals("paused"))
                                grp.stateColor = Color.orange;
                        }
                    }
                }
            }
        }
    }

    if (doc == null) {
        g.setColor(Color.black);
        String text = "No configuration loaded. Select 'Load configuration...' from the file menu.";
        g.drawString(text, (w - SwingUtilities.computeStringWidth(g.getFontMetrics(), text)) / 2, h * 5 / 12);
    } else {
        g.setFont(new Font("Dialog", Font.BOLD, 13));

        Iterator<Terminal> itert = terminalMap.values().iterator();
        while (itert.hasNext()) {
            Terminal t = itert.next();

            // Draw box
            int b = t.isSelected ? SERVERVIEW_SELECTION_BORDER : 1;
            g.setColor(Color.black);
            g.fillRect(t.x + SERVERVIEW_SELECTION_BORDER - b, t.y + SERVERVIEW_SELECTION_BORDER - b,
                    SERVERVIEW_TERMINAL_WIDTH + 2 * b, SERVERVIEW_TERMINAL_HEIGHT + 2 * b);
            g.setColor(t.groupColor == null ? Color.white : t.groupColor);
            g.fillRect(t.x + SERVERVIEW_SELECTION_BORDER, t.y + SERVERVIEW_SELECTION_BORDER,
                    SERVERVIEW_TERMINAL_WIDTH, SERVERVIEW_TERMINAL_HEIGHT);

            // Inner areas
            Rectangle r = new Rectangle(t.x + SERVERVIEW_SELECTION_BORDER + SERVERVIEW_TERMINAL_BORDER,
                    t.y + SERVERVIEW_SELECTION_BORDER + SERVERVIEW_TERMINAL_BORDER,
                    SERVERVIEW_TERMINAL_WIDTH - 2 * SERVERVIEW_TERMINAL_BORDER,
                    g.getFontMetrics().getHeight() + 4);

            g.setColor(Color.white);
            g.fillRect(r.x, r.y, r.width, r.height);
            g.fillRect(r.x, r.y + r.height + SERVERVIEW_TERMINAL_BORDER + 2, r.width,
                    SERVERVIEW_TERMINAL_HEIGHT - 3 * SERVERVIEW_TERMINAL_BORDER - r.height - 2);
            g.setColor(Color.black);
            g.drawRect(r.x, r.y, r.width, r.height);
            g.drawRect(r.x, r.y + r.height + SERVERVIEW_TERMINAL_BORDER + 2, r.width,
                    SERVERVIEW_TERMINAL_HEIGHT - 3 * SERVERVIEW_TERMINAL_BORDER - r.height - 2);

            // Name of terminal and group
            if (server.isaClient(t.tid)) {
                g.drawImage(indicatorIsa.getImage(), r.x + r.width - 20, r.y + SERVERVIEW_TERMINAL_HEIGHT - 26,
                        null);
            }
            g.drawString(t.name + " " + t.groupName, r.x + 4, r.y + r.height - 4);

            double px = r.x + 4;
            double py = r.y + r.height + SERVERVIEW_TERMINAL_BORDER + 5;

            // Draw monitored indicator
            if (t.isMonitored) {
                g.drawImage(indicatorMonitored.getImage(), r.x + r.width - 9, r.y + 3, null);
            }

            // Draw relocated indicator
            if (t.isRelocated) {
                g.drawImage(indicatorRelocated.getImage(), r.x + r.width - 9, r.y + 13, null);
            }

            // Draw online indicator
            r.setBounds(r.x, r.y + r.height, r.width, 3);
            g.setColor(t.isOnline ? Color.green : Color.red);
            g.fillRect(r.x, r.y, r.width, r.height);
            g.setColor(Color.black);
            g.drawRect(r.x, r.y, r.width, r.height);

            // Roles
            if (t.roles.length() > 0) {
                LineBreakMeasurer lbm = new LineBreakMeasurer(new AttributedString(t.roles).getIterator(),
                        new FontRenderContext(null, false, true));

                TextLayout layout;
                while ((layout = lbm
                        .nextLayout(SERVERVIEW_TERMINAL_WIDTH - 2 * SERVERVIEW_TERMINAL_BORDER)) != null) {
                    if (py < t.y + SERVERVIEW_TERMINAL_HEIGHT) {
                        py += layout.getAscent();
                        layout.draw((Graphics2D) g, (int) px, (int) py);
                        py += layout.getDescent() + layout.getLeading();
                    }
                }
            }
        }

        // Draw group indicators
        int nbrGroupsInRow = w
                / (2 * Constants.SERVERVIEW_SELECTION_BORDER + 2 + Constants.SERVERVIEW_GROUP_WIDTH);
        if (nbrGroupsInRow < 1)
            nbrGroupsInRow = 1;
        int nbrGroupRows = (groupList.size() + nbrGroupsInRow - 1) / nbrGroupsInRow;

        int innerWidth = Constants.SERVERVIEW_GROUP_WIDTH;
        int innerHeight = g.getFontMetrics().getHeight() + 5;

        int outerWidth = innerWidth + 2 * Constants.SERVERVIEW_SELECTION_BORDER + 2;
        int outerHeight = innerHeight + 2 * Constants.SERVERVIEW_SELECTION_BORDER + 2;

        int x = 0;
        int y = h - outerHeight * nbrGroupRows;

        g.setColor(Color.white);
        g.fillRect(0, y, w, h - y);
        g.setColor(Color.black);
        g.drawLine(0, y - 1, w - 1, y - 1);

        Iterator<Group> iterg = groupList.iterator();
        while (iterg.hasNext()) {
            Group grp = iterg.next();

            // Group box
            grp.boundingRect.setBounds(x, y, outerWidth, outerHeight);
            int b = grp.isSelected ? Constants.SERVERVIEW_SELECTION_BORDER : 1;
            g.setColor(Color.black);
            g.fillRect(x + Constants.SERVERVIEW_SELECTION_BORDER - b + 1,
                    y + Constants.SERVERVIEW_SELECTION_BORDER - b + 1, innerWidth + 2 * b, innerHeight + 2 * b);
            g.setColor(grp.color);
            g.fillRect(x + Constants.SERVERVIEW_SELECTION_BORDER + 1,
                    y + Constants.SERVERVIEW_SELECTION_BORDER + 1, innerWidth, innerHeight);

            g.setColor(Color.black);
            g.drawString(grp.name, x + Constants.SERVERVIEW_SELECTION_BORDER + 4,
                    y + Constants.SERVERVIEW_SELECTION_BORDER + innerHeight - 4 + 1);

            // Draw started indicator
            g.setColor(grp.stateColor);
            g.fillRect(x + Constants.SERVERVIEW_SELECTION_BORDER + 1,
                    y + Constants.SERVERVIEW_SELECTION_BORDER + 1, innerWidth, 2);
            g.setColor(Color.black);
            g.drawLine(x + Constants.SERVERVIEW_SELECTION_BORDER + 1,
                    y + Constants.SERVERVIEW_SELECTION_BORDER + 3,
                    x + Constants.SERVERVIEW_SELECTION_BORDER + 1 + innerWidth,
                    y + Constants.SERVERVIEW_SELECTION_BORDER + 3);

            x += outerWidth;
            if ((x + outerWidth) > w) {
                x = 0;
                y += outerHeight;
            }
        }
    }

    // Store cached version
    documentVersion = updateDocumentVersion;

    g.setColor(storedCol);
    g.setFont(storedFont);
}

From source file:SWTGraphics2D.java

/**
 * Returns the font render context.//from www  .  j  a va  2s  .com
 *
 * @return The font render context.
 */
public FontRenderContext getFontRenderContext() {
    FontRenderContext fontRenderContext = new FontRenderContext(new AffineTransform(), true, true);
    return fontRenderContext;
}

From source file:DefaultGraphics2D.java

/**
 * Get the rendering context of the <code>Font</code> within this
 * <code>Graphics2D</code> context. The {@link FontRenderContext}
 * encapsulates application hints such as anti-aliasing and fractional
 * metrics, as well as target device specific information such as
 * dots-per-inch. This information should be provided by the application when
 * using objects that perform typographical formatting, such as
 * <code>Font</code> and <code>TextLayout</code>. This information should
 * also be provided by applications that perform their own layout and need
 * accurate measurements of various characteristics of glyphs such as advance
 * and line height when various rendering hints have been applied to the text
 * rendering.//  w  w  w.ja  v  a2  s . co  m
 * 
 * @return a reference to an instance of FontRenderContext.
 * @see java.awt.font.FontRenderContext
 * @see java.awt.Font#createGlyphVector(FontRenderContext,char[])
 * @see java.awt.font.TextLayout
 * @since JDK1.2
 */
public FontRenderContext getFontRenderContext() {
    //
    // Find if antialiasing should be used.
    //
    Object antialiasingHint = hints.get(RenderingHints.KEY_TEXT_ANTIALIASING);
    boolean isAntialiased = true;
    if (antialiasingHint != RenderingHints.VALUE_TEXT_ANTIALIAS_ON
            && antialiasingHint != RenderingHints.VALUE_TEXT_ANTIALIAS_DEFAULT) {

        // If antialias was not turned off, then use the general rendering
        // hint.
        if (antialiasingHint != RenderingHints.VALUE_TEXT_ANTIALIAS_OFF) {
            antialiasingHint = hints.get(RenderingHints.KEY_ANTIALIASING);

            // Test general hint
            if (antialiasingHint != RenderingHints.VALUE_ANTIALIAS_ON
                    && antialiasingHint != RenderingHints.VALUE_ANTIALIAS_DEFAULT) {
                // Antialiasing was not requested. However, if it was not turned
                // off explicitly, use it.
                if (antialiasingHint == RenderingHints.VALUE_ANTIALIAS_OFF)
                    isAntialiased = false;
            }
        } else
            isAntialiased = false;

    }

    //
    // Find out whether fractional metrics should be used.
    //
    boolean useFractionalMetrics = true;
    if (hints.get(RenderingHints.KEY_FRACTIONALMETRICS) == RenderingHints.VALUE_FRACTIONALMETRICS_OFF)
        useFractionalMetrics = false;

    FontRenderContext frc = new FontRenderContext(defaultTransform, isAntialiased, useFractionalMetrics);
    return frc;
}

From source file:org.forester.archaeopteryx.TreePanel.java

final private int paintTaxonomy(final Graphics2D g, final PhylogenyNode node, final boolean is_in_found_nodes,
        final boolean to_pdf, final boolean to_graphics_file) {
    final Taxonomy taxonomy = node.getNodeData().getTaxonomy();
    g.setFont(getTreeFontSet().getLargeItalicFont());
    if ((to_pdf || to_graphics_file) && getOptions().isPrintBlackAndWhite()) {
        g.setColor(Color.BLACK);//  w w  w.j  a  va 2 s  .  co m
    } else if (is_in_found_nodes) {
        g.setFont(getTreeFontSet().getLargeItalicFont().deriveFont(TreeFontSet.BOLD_AND_ITALIC));
        g.setColor(getTreeColorSet().getFoundColor());
    } else if (getControlPanel().isColorAccordingToTaxonomy()) {
        g.setColor(getTaxonomyBasedColor(node));
    } else {
        g.setColor(getTreeColorSet().getTaxonomyColor());
    }
    final double start_x = node.getXcoord() + 3 + TreePanel.HALF_BOX_SIZE;
    final double start_y = node.getYcoord()
            + (getTreeFontSet()._fm_large.getAscent() / (node.getNumberOfDescendants() == 1 ? 1 : 3.0));
    _sb.setLength(0);
    if (_control_panel.isShowTaxonomyCode() && !ForesterUtil.isEmpty(taxonomy.getTaxonomyCode())) {
        _sb.append(taxonomy.getTaxonomyCode());
        _sb.append(" ");
    }
    if (_control_panel.isShowTaxonomyNames()) {
        if (!ForesterUtil.isEmpty(taxonomy.getScientificName())
                && !ForesterUtil.isEmpty(taxonomy.getCommonName())) {
            _sb.append(taxonomy.getScientificName());
            _sb.append(" (");
            _sb.append(taxonomy.getCommonName());
            _sb.append(") ");
        } else if (!ForesterUtil.isEmpty(taxonomy.getScientificName())) {
            _sb.append(taxonomy.getScientificName());
            _sb.append(" ");
        } else if (!ForesterUtil.isEmpty(taxonomy.getCommonName())) {
            _sb.append(taxonomy.getCommonName());
            _sb.append(" ");
        }
    }
    final String label = _sb.toString();
    /* GUILHEM_BEG */
    if ((label.length() > 0) && (node.getNodeData().isHasSequence())
            && node.getNodeData().getSequence().equals(_query_sequence)) {
        // invert font color and background color to show that this is the query sequence
        final Rectangle2D nodeTextBounds = new TextLayout(label, g.getFont(),
                new FontRenderContext(null, false, false)).getBounds();
        g.fillRect((int) start_x - 1, (int) start_y - 8, (int) nodeTextBounds.getWidth() + 4, 11);
        g.setColor(getTreeColorSet().getBackgroundColor());
    }
    /* GUILHEM_END */
    TreePanel.drawString(label, start_x, start_y, g);
    if (is_in_found_nodes) {
        return getTreeFontSet()._fm_large_italic_bold.stringWidth(label);
    } else {
        return getTreeFontSet()._fm_large_italic.stringWidth(label);
    }
}

From source file:org.apache.jetspeed.security.mfa.impl.CaptchaImageResource.java

public void init() {
    boolean emptyBackground = true;
    if (config.isUseImageBackground() && background != null) {
        ByteArrayInputStream is = new ByteArrayInputStream(background);
        JPEGImgDecoder decoder = new DefaultJPEGImgDecoder();
        try {/*  w  w  w  .ja  va 2s .c  o m*/
            this.image = decoder.decodeAsBufferedImage(is);
            this.width = image.getWidth();
            this.height = image.getHeight();
            emptyBackground = false;
        } catch (Exception e) {
            emptyBackground = true;
        }
    }
    if (emptyBackground) {
        this.width = config.getTextMarginLeft() * 2;
        this.height = config.getTextMarginBottom() * 6;
    }
    char[] chars = challengeId.toCharArray();
    charAttsList = new ArrayList();
    TextLayout text = null;
    AffineTransform textAt = null;
    String[] fontNames = config.getFontNames();
    for (int i = 0; i < chars.length; i++) {
        // font name
        String fontName = (fontNames.length == 1) ? fontNames[0] : fontNames[randomInt(0, fontNames.length)];

        // rise
        int rise = config.getTextRiseRange();
        if (rise > 0) {
            rise = randomInt(config.getTextMarginBottom(),
                    config.getTextMarginBottom() + config.getTextRiseRange());
        }

        if (config.getTextShear() > 0.0 || config.getTextRotation() > 0) {
            // rotation
            double dRotation = 0.0;
            if (config.getTextRotation() > 0) {
                dRotation = Math.toRadians(randomInt(-(config.getTextRotation()), config.getTextRotation()));
            }

            // shear
            double shearX = 0.0;
            double shearY = 0.0;
            if (config.getTextShear() > 0.0) {
                Random ran = new Random();
                shearX = ran.nextDouble() * config.getTextShear();
                shearY = ran.nextDouble() * config.getTextShear();
            }
            CharAttributes cf = new CharAttributes(chars[i], fontName, dRotation, rise, shearX, shearY);
            charAttsList.add(cf);
            text = new TextLayout(chars[i] + "", getFont(fontName),
                    new FontRenderContext(null, config.isFontAntialiasing(), false));
            textAt = new AffineTransform();
            if (config.getTextRotation() > 0)
                textAt.rotate(dRotation);
            if (config.getTextShear() > 0.0)
                textAt.shear(shearX, shearY);
        } else {
            CharAttributes cf = new CharAttributes(chars[i], fontName, 0, rise, 0.0, 0.0);
            charAttsList.add(cf);
        }
        if (emptyBackground) {
            Shape shape = text.getOutline(textAt);
            //                this.width += text.getBounds().getWidth();
            this.width += (int) shape.getBounds2D().getWidth();
            this.width += config.getTextSpacing() + 1;
            if (this.height < (int) shape.getBounds2D().getHeight() + rise) {
                this.height = (int) shape.getBounds2D().getHeight() + rise;
            }
        }
    }
    if (emptyBackground) {
        this.image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D gfx = (Graphics2D) this.image.getGraphics();
        gfx.setBackground(Color.WHITE);
        gfx.clearRect(0, 0, width, height);
    }
}