Example usage for java.awt Graphics2D getFontMetrics

List of usage examples for java.awt Graphics2D getFontMetrics

Introduction

In this page you can find the example usage for java.awt Graphics2D getFontMetrics.

Prototype

public abstract FontMetrics getFontMetrics(Font f);

Source Link

Document

Gets the font metrics for the specified font.

Usage

From source file:ala.soils2sat.DrawingUtils.java

/**
 * Draws the text by creating a rectange centered around x, y
 *
 * @param g/*from  www  .  j av  a2 s  .  co  m*/
 * @param font
 * @param x
 * @param y
 * @return The rectangle that bounds the text
 */
public static Rectangle drawCentredText(Graphics2D g, Font font, String text, int x, int y) {
    g.setFont(font);
    FontMetrics fm = g.getFontMetrics(font);

    setPreferredAliasingMode(g);

    Rectangle ret = new Rectangle(x, y, 0, 0);

    if (text == null) {
        return ret;
    }
    String[] alines = text.split("\\n");
    ArrayList<String> lines = new ArrayList<String>();
    for (String s : alines) {
        if (s.length() > 0) {
            lines.add(s);
        }
    }
    int numlines = lines.size();
    if (numlines > 0) {
        int maxwidth = 0;
        int totalheight = 0;
        for (int idx = 0; idx < numlines; ++idx) {
            String line = lines.get(idx);
            int stringWidth = fm.stringWidth(line);
            if (stringWidth > maxwidth) {
                maxwidth = stringWidth;
            }
            totalheight += fm.getAscent() + fm.getDescent();
        }
        ret.width = maxwidth;
        ret.height = totalheight;
        ret.x = x - (maxwidth / 2);
        ret.y = y - (totalheight / 2);

        drawString(g, font, text, ret, TEXT_ALIGN_CENTER);

        return ret;
    }
    return ret;

}

From source file:net.sf.webphotos.tools.Thumbnail.java

private static Image estampar(Image im) {
    try {/*from   www . java  2s .  c  o m*/
        Image temp = new ImageIcon(im).getImage();

        BufferedImage buf = new BufferedImage(temp.getWidth(null), temp.getHeight(null),
                BufferedImage.TYPE_INT_RGB);

        Graphics2D g2 = (Graphics2D) buf.getGraphics();

        g2.drawImage(temp, 0, 0, null);
        g2.setBackground(Color.BLUE);

        Dimension dimensaoFoto = new Dimension(im.getWidth(null), im.getHeight(null));

        // aplicar texto
        if (texto != null) {
            Util.out.println("aplicando texto " + texto);

            Font fonte = new Font(txFamilia, txEstilo, txTamanho);
            g2.setFont(fonte);
            FontMetrics fm = g2.getFontMetrics(fonte);
            Dimension dimensaoTexto = new Dimension(fm.stringWidth(texto), fm.getHeight());
            Point posTexto = calculaPosicao(dimensaoFoto, dimensaoTexto, txMargem, txPosicao);

            g2.setPaint(txCorFundo);
            g2.drawString(texto, (int) posTexto.getX() + 1, (int) posTexto.getY() + 1 + fm.getHeight());
            g2.setPaint(txCorFrente);
            g2.drawString(texto, (int) posTexto.getX(), (int) posTexto.getY() + fm.getHeight());
        }

        // aplicar marca dagua
        if (marcadagua != null) {
            Image marca = new ImageIcon(marcadagua).getImage();
            int rule = AlphaComposite.SRC_OVER;
            float alpha = (float) mdTransparencia / 100;
            Point pos = calculaPosicao(dimensaoFoto, new Dimension(marca.getWidth(null), marca.getHeight(null)),
                    mdMargem, mdPosicao);

            g2.setComposite(AlphaComposite.getInstance(rule, alpha));
            g2.drawImage(marca, (int) pos.getX(), (int) pos.getY(), null);
        }

        g2.dispose();
        //return (Image) buf;
        return Toolkit.getDefaultToolkit().createImage(buf.getSource());
    } catch (Exception e) {
        Util.err.println("[Thumbnail.estampar]/ERRO: Inesperado - " + e.getMessage());
        e.printStackTrace(Util.err);
        return im;
    }
}

From source file:org.lnicholls.galleon.util.Tools.java

public static FontMetrics getFontMetrics(Font font) {
    Graphics2D graphics2D = (Graphics2D) buffer.getGraphics();
    try {// w  w  w . j a  v a  2s . c  om
        FontMetrics fontMetrics = graphics2D.getFontMetrics(font);
        return fontMetrics;
    } finally {
        graphics2D.dispose();
    }
}

From source file:net.sourceforge.processdash.ui.web.CGIChartBase.java

protected Font getFontSizeToFit(Graphics2D g, Font baseFont, String text, int width) {
    FontMetrics m = g.getFontMetrics(baseFont);
    int currentWidth = m.stringWidth(text);
    Font result = baseFont;/*from   www  .  j a  v a  2s  .c  o m*/

    int maxIter = 100;
    while (currentWidth > width && maxIter-- > 0) {
        result = result.deriveFont(result.getSize2D() * 0.95f);
        m = g.getFontMetrics(result);
        currentWidth = m.stringWidth(text);
    }

    return result;
}

From source file:com.celements.photo.image.GenerateThumbnail.java

private FontMetrics calcWatermarkFontSize(String watermark, int width, Graphics2D g2d) {
    FontMetrics metrics;/*from w w  w  . ja  v  a2s.c o  m*/
    int fontSize = 1;
    do {
        metrics = g2d.getFontMetrics(new Font(g2d.getFont().getFontName(), Font.BOLD, fontSize));
        fontSize++;
    } while (metrics.stringWidth(watermark) < (0.8 * width));
    return metrics;
}

From source file:com.celements.photo.image.GenerateThumbnail.java

private FontMetrics calcCopyrightFontSize(String copyright, int width, Graphics2D g2d) {
    FontMetrics metrics;/*w  w  w  .j  a  va 2 s. c  o m*/
    int fontSize = 16;
    do {
        metrics = g2d.getFontMetrics(new Font(g2d.getFont().getFontName(), Font.BOLD, fontSize));
        fontSize--;
    } while ((fontSize > 0) && (metrics.stringWidth(copyright) > (width / 3)));
    return metrics;
}

From source file:net.sf.fspdfs.chartthemes.spring.ScaledDialValueIndicator.java

/**
 * Draws the background to the specified graphics device.  If the dial
 * frame specifies a window, the clipping region will already have been
 * set to this window before this method is called.
 *
 * @param g2  the graphics device (<code>null</code> not permitted).
 * @param plot  the plot (ignored here).
 * @param frame  the dial frame (ignored here).
 * @param view  the view rectangle (<code>null</code> not permitted).
 *//*from   www. j a  v  a 2  s.co  m*/
public void draw(Graphics2D g2, DialPlot plot, Rectangle2D frame, Rectangle2D view) {

    // work out the anchor point
    Rectangle2D f = DialPlot.rectangleByRadius(frame, getRadius(), this.getRadius());
    Arc2D arc = new Arc2D.Double(f, this.getAngle(), 0.0, Arc2D.OPEN);
    Point2D pt = arc.getStartPoint();

    // calculate the bounds of the template value
    FontMetrics fm = g2.getFontMetrics(this.getFont());
    String s = this.getNumberFormat().format(this.getTemplateValue());
    Rectangle2D tb = TextUtilities.getTextBounds(s, g2, fm);

    // align this rectangle to the frameAnchor
    Rectangle2D bounds = RectangleAnchor.createRectangle(new Size2D(tb.getWidth(), tb.getHeight()), pt.getX(),
            pt.getY(), this.getFrameAnchor());

    // add the insets
    Rectangle2D fb = this.getInsets().createOutsetRectangle(bounds);

    // draw the background
    g2.setPaint(this.getBackgroundPaint());
    g2.fill(fb);

    // draw the border
    g2.setStroke(this.getOutlineStroke());
    g2.setPaint(this.getOutlinePaint());
    g2.draw(fb);

    // now find the text anchor point
    String valueStr = this.getNumberFormat()
            .format(ChartThemesUtilities.getScaledValue(plot.getValue(this.getDatasetIndex()), scale));
    Point2D pt2 = RectangleAnchor.coordinates(bounds, this.getValueAnchor());
    g2.setPaint(this.getPaint());
    g2.setFont(this.getFont());
    TextUtilities.drawAlignedString(valueStr, g2, (float) pt2.getX(), (float) pt2.getY(), this.getTextAnchor());

}

From source file:net.sf.jasperreports.chartthemes.spring.ScaledDialValueIndicator.java

/**
 * Draws the background to the specified graphics device.  If the dial
 * frame specifies a window, the clipping region will already have been
 * set to this window before this method is called.
 *
 * @param g2  the graphics device (<code>null</code> not permitted).
 * @param plot  the plot (ignored here).
 * @param frame  the dial frame (ignored here).
 * @param view  the view rectangle (<code>null</code> not permitted).
 *///w w w  . j av a 2 s .c  o  m
@Override
public void draw(Graphics2D g2, DialPlot plot, Rectangle2D frame, Rectangle2D view) {

    // work out the anchor point
    Rectangle2D f = DialPlot.rectangleByRadius(frame, getRadius(), this.getRadius());
    Arc2D arc = new Arc2D.Double(f, this.getAngle(), 0.0, Arc2D.OPEN);
    Point2D pt = arc.getStartPoint();

    // calculate the bounds of the template value
    FontMetrics fm = g2.getFontMetrics(this.getFont());
    String s = this.getNumberFormat().format(this.getTemplateValue());
    Rectangle2D tb = TextUtilities.getTextBounds(s, g2, fm);

    // align this rectangle to the frameAnchor
    Rectangle2D bounds = RectangleAnchor.createRectangle(new Size2D(tb.getWidth(), tb.getHeight()), pt.getX(),
            pt.getY(), this.getFrameAnchor());

    // add the insets
    Rectangle2D fb = this.getInsets().createOutsetRectangle(bounds);

    // draw the background
    g2.setPaint(this.getBackgroundPaint());
    g2.fill(fb);

    // draw the border
    g2.setStroke(this.getOutlineStroke());
    g2.setPaint(this.getOutlinePaint());
    g2.draw(fb);

    // now find the text anchor point
    String valueStr = this.getNumberFormat()
            .format(ChartThemesUtilities.getScaledValue(plot.getValue(this.getDatasetIndex()), scale));
    Point2D pt2 = RectangleAnchor.coordinates(bounds, this.getValueAnchor());
    g2.setPaint(this.getPaint());
    g2.setFont(this.getFont());
    TextUtilities.drawAlignedString(valueStr, g2, (float) pt2.getX(), (float) pt2.getY(), this.getTextAnchor());

}

From source file:pl.edu.icm.visnow.system.main.VisNow.java

private static void renderSplashFrame(float progress, String loadText, String bottomTextUpperLine,
        String bottomTextLowerLine) {
    if (splash == null) {
        return;//from   w  w  w  .j  a v a2 s . c  o m
    }

    try {
        Graphics2D g = splash.createGraphics();
        if (g == null) {
            return;
        }

        if (!splash.isVisible())
            return;

        Rectangle bounds = splash.getBounds();
        Font f = g.getFont();
        FontMetrics fm = g.getFontMetrics(f);
        java.awt.geom.Rectangle2D rect = fm.getStringBounds(loadText, g);
        int texth = (int) Math.ceil(rect.getHeight());
        g.setComposite(AlphaComposite.Clear);
        //g.setColor(Color.RED);
        g.fillRect(PROGRESS_TEXT_X_POSITION, bounds.height - PROGRESS_TEXT_Y_MARGIN - texth - 5,
                bounds.width - PROGRESS_TEXT_X_POSITION, texth + 10);

        g.setFont(lowerLineFont);
        fm = g.getFontMetrics(g.getFont());
        rect = fm.getStringBounds(bottomTextLowerLine, g);
        int lowerLineTextHeight = (int) Math.ceil(rect.getHeight());
        g.fillRect(BOTTOM_TEXT_X_MARGIN, bounds.height - BOTTOM_TEXT_Y_MARGIN - lowerLineTextHeight - 5,
                bounds.width - BOTTOM_TEXT_X_MARGIN, lowerLineTextHeight + 10);

        g.setFont(f);
        fm = g.getFontMetrics(g.getFont());
        rect = fm.getStringBounds(bottomTextUpperLine, g);
        texth = (int) Math.ceil(rect.getHeight());
        g.fillRect(BOTTOM_TEXT_X_MARGIN, bounds.height - lowerLineTextHeight - BOTTOM_TEXT_Y_MARGIN - texth - 5,
                bounds.width - BOTTOM_TEXT_X_MARGIN, lowerLineTextHeight + 10);

        g.setPaintMode();
        //        g.setColor(Color.BLACK);
        g.setColor(new Color(0, 75, 50));
        g.drawString(loadText, PROGRESS_TEXT_X_POSITION, bounds.height - PROGRESS_TEXT_Y_MARGIN);
        g.drawString(bottomTextUpperLine, BOTTOM_TEXT_X_MARGIN,
                bounds.height - lowerLineTextHeight - BOTTOM_TEXT_Y_MARGIN);
        g.setFont(lowerLineFont);
        g.drawString(bottomTextLowerLine, BOTTOM_TEXT_X_MARGIN, bounds.height - BOTTOM_TEXT_Y_MARGIN);
        g.setFont(f);

        //        g.setColor(Color.BLACK);
        g.setColor(new Color(0, 150, 100));
        g.drawRect(PROGRESS_BAR_X_MARGIN, bounds.height - PROGRESS_BAR_Y_MARGIN,
                bounds.width - PROGRESS_BAR_X_MARGIN, PROGRESS_BAR_HEIGHT);
        int progressWidth = bounds.width - 2 * PROGRESS_BAR_X_MARGIN;
        int done = (int) (progressWidth * progress);
        g.fillRect(PROGRESS_BAR_X_MARGIN, bounds.height - PROGRESS_BAR_Y_MARGIN, PROGRESS_BAR_X_MARGIN + done,
                PROGRESS_BAR_HEIGHT);
        if (progress >= 1.0f) {
            g.fillRect(PROGRESS_BAR_X_MARGIN, bounds.height - PROGRESS_BAR_Y_MARGIN,
                    bounds.width - PROGRESS_BAR_X_MARGIN, PROGRESS_BAR_HEIGHT);
        }

        splash.update();
    } catch (IllegalStateException ex) {
    }
}

From source file:figs.treeVisualization.gui.TimeAxisTree2DPanel.java

/**
 * Estimate the maximum date width, this also tacks on the tick mark outside length.
 *
 * @param g2/*from w  w w .  j  a  v a2s .com*/
 */
private void estimateMaximumDateWidth(Graphics2D g2) {
    double maxWidth = 0.0;
    RectangleInsets insets = this.fDateAxis.getLabelInsets();
    FontMetrics fm = g2.getFontMetrics(this.fDateAxis.getTickLabelFont());
    DateFormat formatter = this.fDateAxis.getDateFormatOverride();

    for (Iterator<Calendar> i = this.fLeafDates.values().iterator(); i.hasNext();) {
        Date tickDate = i.next().getTime();
        String tickLabel;
        if (formatter != null) {
            tickLabel = formatter.format(tickDate);
        } else {
            tickLabel = this.fDateAxis.getTickUnit().dateToString(tickDate);
        }
        Rectangle2D labelBounds = TextUtilities.getTextBounds(tickLabel, g2, fm);
        if (labelBounds.getWidth() + insets.getLeft() + insets.getRight() > maxWidth) {
            maxWidth = labelBounds.getWidth() + insets.getLeft() + insets.getRight();
        }
    }

    this.fEstMaxDateWidth = maxWidth + this.fDateAxis.getTickMarkOutsideLength();
}