Example usage for java.awt Graphics2D setFont

List of usage examples for java.awt Graphics2D setFont

Introduction

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

Prototype

public abstract void setFont(Font font);

Source Link

Document

Sets this graphics context's font to the specified font.

Usage

From source file:Main.java

public static BufferedImage createRotatedTextImage(String text, int angle, Font ft) {
    Graphics2D g2d = null;
    try {/*from  w  w  w. j  av a2s.  c o m*/
        if (text == null || text.trim().length() == 0) {
            return null;
        }

        BufferedImage stringImage = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);

        g2d = (Graphics2D) stringImage.getGraphics();
        g2d.setFont(ft);

        FontMetrics fm = g2d.getFontMetrics();
        Rectangle2D bounds = fm.getStringBounds(text, g2d);

        TextLayout tl = new TextLayout(text, ft, g2d.getFontRenderContext());

        g2d.dispose();
        g2d = null;

        return createRotatedImage(tl, (int) bounds.getWidth(), (int) bounds.getHeight(), angle);
    } catch (Exception e) {
        e.printStackTrace();

        if (g2d != null) {
            g2d.dispose();
        }
    }

    return null;
}

From source file:net.noday.core.utils.Captcha.java

public static BufferedImage gen(String text, int width, int height) throws IOException {
    BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
    Graphics2D g = (Graphics2D) bi.getGraphics();
    g.setColor(Color.GRAY);/*from w w  w  .j  a  va2  s  .  c o  m*/
    g.fillRect(0, 0, width, height);
    for (int i = 0; i < 10; i++) {
        g.setColor(randColor(150, 250));
        g.drawOval(random.nextInt(110), random.nextInt(24), 5 + random.nextInt(10), 5 + random.nextInt(10));
        Font f = new Font("Arial", Font.ITALIC, 20);
        g.setFont(f);
        g.setColor(randColor(10, 240));
        g.drawString(text, 4, 24);
    }
    return bi;
}

From source file:org.gitools.ui.app.heatmap.drawer.AbstractHeatmapDrawer.java

/**
 * Automatically change the font size to fit in the cell height.
 *
 * @param g           the Graphics2D object
 * @param cellHeight  the cell height// ww  w  .ja v  a2s . c om
 * @param minFontSize the min font size
 * @return Returns true if the new font size fits in the cell height, false if it doesn't fit.
 */
protected static boolean calculateFontSize(Graphics2D g, int cellHeight, int minFontSize) {

    float fontHeight = g.getFontMetrics().getHeight();

    float fontSize = g.getFont().getSize();
    while (fontHeight > (cellHeight - 2) && fontSize > minFontSize) {
        fontSize--;
        g.setFont(g.getFont().deriveFont(fontSize));
        fontHeight = g.getFontMetrics().getHeight();
    }

    return fontHeight <= (cellHeight - 2);
}

From source file:ala.soils2sat.DrawingUtils.java

/**
 * Draws the text by creating a rectange centered around x, y
 *
 * @param g/* ww  w  .  ja va  2s .c om*/
 * @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:com.simiacryptus.util.Util.java

/**
 * To image buffered image.// w w  w  .  j  a  v  a 2  s  . com
 *
 * @param component the component
 * @return the buffered image
 */
public static BufferedImage toImage(@javax.annotation.Nonnull final Component component) {
    try {
        com.simiacryptus.util.Util.layout(component);
        @javax.annotation.Nonnull
        final BufferedImage img = new BufferedImage(component.getWidth(), component.getHeight(),
                BufferedImage.TYPE_INT_ARGB_PRE);
        final Graphics2D g = img.createGraphics();
        g.setColor(component.getForeground());
        g.setFont(component.getFont());
        component.print(g);
        return img;
    } catch (@javax.annotation.Nonnull final Exception e) {
        return null;
    }
}

From source file:net.semanticmetadata.lire.utils.FileUtils.java

public static void saveImageResultsToPng(String prefix, TopDocs hits, String queryImage, IndexReader ir)
        throws IOException {
    LinkedList<BufferedImage> results = new LinkedList<BufferedImage>();
    int width = 0;
    for (int i = 0; i < Math.min(hits.scoreDocs.length, 10); i++) {
        // hits.score(i)
        // hits.doc(i).get("descriptorImageIdentifier")
        BufferedImage tmp = ImageIO
                .read(new FileInputStream(ir.document(hits.scoreDocs[i].doc).get("descriptorImageIdentifier")));
        if (tmp.getHeight() > 200) {
            double factor = 200d / ((double) tmp.getHeight());
            tmp = ImageUtils.scaleImage(tmp, (int) (tmp.getWidth() * factor), 200);
        }/*from  w  ww . j a v  a2 s. c  om*/
        width += tmp.getWidth() + 5;
        results.add(tmp);
    }
    BufferedImage result = new BufferedImage(width, 220, BufferedImage.TYPE_INT_RGB);
    Graphics2D g2 = (Graphics2D) result.getGraphics();
    g2.setColor(Color.black);
    g2.clearRect(0, 0, result.getWidth(), result.getHeight());
    g2.setColor(Color.green);
    g2.setFont(Font.decode("\"Arial\", Font.BOLD, 12"));
    int offset = 0;
    int count = 0;
    for (Iterator<BufferedImage> iterator = results.iterator(); iterator.hasNext();) {
        BufferedImage next = iterator.next();
        g2.drawImage(next, offset, 20, null);
        g2.drawString(hits.scoreDocs[count].score + "", offset + 5, 12);
        offset += next.getWidth() + 5;
        count++;
    }
    ImageIO.write(result, "PNG", new File(prefix + "_" + (System.currentTimeMillis() / 1000) + ".png"));
}

From source file:net.semanticmetadata.lire.utils.FileUtils.java

public static void saveImageResultsToPng(String prefix, ImageSearchHits hits, String queryImage,
        IndexReader reader) throws IOException {
    LinkedList<BufferedImage> results = new LinkedList<BufferedImage>();
    int width = 0;
    for (int i = 0; i < hits.length(); i++) {
        // hits.score(i)
        // hits.doc(i).get("descriptorImageIdentifier")
        BufferedImage tmp = ImageIO.read(new FileInputStream(
                reader.document(hits.documentID(i)).getValues(DocumentBuilder.FIELD_NAME_IDENTIFIER)[0]));
        //            if (tmp.getHeight() > 200) {
        double factor = 200d / ((double) tmp.getHeight());
        tmp = ImageUtils.scaleImage(tmp, (int) (tmp.getWidth() * factor), 200);
        //            }
        width += tmp.getWidth() + 5;/*ww  w  .j  a  v  a 2  s .  c o  m*/
        results.add(tmp);
    }
    BufferedImage result = new BufferedImage(width, 220, BufferedImage.TYPE_INT_RGB);
    Graphics2D g2 = (Graphics2D) result.getGraphics();
    g2.setColor(Color.white);
    g2.setBackground(Color.white);
    g2.clearRect(0, 0, result.getWidth(), result.getHeight());
    g2.setColor(Color.black);
    g2.setFont(Font.decode("\"Arial\", Font.BOLD, 12"));
    int offset = 0;
    int count = 0;
    for (Iterator<BufferedImage> iterator = results.iterator(); iterator.hasNext();) {
        BufferedImage next = iterator.next();
        g2.drawImage(next, offset, 20, null);
        g2.drawString(hits.score(count) + "", offset + 5, 12);
        offset += next.getWidth() + 5;
        count++;
    }
    ImageIO.write(result, "PNG", new File(prefix + "_" + (System.currentTimeMillis() / 1000) + ".png"));
}

From source file:juicebox.tools.utils.juicer.apa.APAPlotter.java

/**
 * Plot number value axis for color scale bar.
 *
 * @param g2      graphics2D object/*from  w  w  w  . ja v  a2  s.co  m*/
 * @param heatMap object
 */
private static void plotColorScaleValues(Graphics2D g2, HeatChart heatMap) {
    // size, increment calculations
    double valIncrement = Math.max(heatMap.getDataRange() / ((double) numDivisions), epsilon);
    double depthIncrement = ((double) (fullHeight - 2 * colorScaleVerticalMargin)) / ((double) numDivisions);
    int verticalDepth = fullHeight - colorScaleVerticalMargin;
    int csBarRightEdgeX = fullWidth - colorScaleHorizontalMargin - extraWidthBuffer;

    // formatting
    g2.setFont(heatMap.getAxisValuesFont());
    DecimalFormat df = new DecimalFormat("0.#");

    // draw each tick mark and its value
    for (double i = heatMap.getLowValue(); i <= heatMap
            .getHighValue(); i += valIncrement, verticalDepth -= depthIncrement) {

        if (i > heatMap.getHighValue() - epsilon)
            verticalDepth = colorScaleVerticalMargin;
        g2.drawString(df.format(i), csBarRightEdgeX + 5, verticalDepth); // value
        g2.drawLine(csBarRightEdgeX - 5, verticalDepth, csBarRightEdgeX, verticalDepth); // tick mark
    }
}

From source file:weka.core.ChartUtils.java

/**
 * Render a combined histogram and pie chart from summary data
 * /*from  w  w  w.  ja  v  a 2s.c  o m*/
 * @param width the width of the resulting image
 * @param height the height of the resulting image
 * @param values the values for the chart
 * @param freqs the corresponding frequencies
 * @param additionalArgs optional arguments to the renderer (may be null)
 * @return a buffered image
 * @throws Exception if a problem occurs
 */
public static BufferedImage renderCombinedPieAndHistogramFromSummaryData(int width, int height,
        List<String> values, List<Double> freqs, List<String> additionalArgs) throws Exception {

    String plotTitle = "Combined Chart";
    String userTitle = getOption(additionalArgs, "-title");
    plotTitle = (userTitle != null) ? userTitle : plotTitle;

    List<String> opts = new ArrayList<String>();
    opts.add("-title=distribution");
    BufferedImage pie = renderPieChartFromSummaryData(width / 2, height, values, freqs, false, true, opts);

    opts.clear();
    opts.add("-title=histogram");
    BufferedImage hist = renderHistogramFromSummaryData(width / 2, height, values, freqs, opts);

    BufferedImage img = new BufferedImage(width, height + 20, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2d = img.createGraphics();
    g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_GASP);
    g2d.setFont(new Font("SansSerif", Font.BOLD, 12));
    g2d.setColor(Color.lightGray);
    g2d.fillRect(0, 0, width, height + 20);
    g2d.setColor(Color.black);
    FontMetrics fm = g2d.getFontMetrics();
    int fh = fm.getHeight();
    int sw = fm.stringWidth(plotTitle);

    g2d.drawImage(pie, 0, 20, null);
    g2d.drawImage(hist, width / 2 + 1, 20, null);
    g2d.drawString(plotTitle, width / 2 - sw / 2, fh + 2);
    g2d.dispose();

    return img;
}

From source file:weka.core.ChartUtils.java

/**
 * Render a combined histogram and box plot chart from summary data
 * //from  ww w.  ja v a 2 s .  c o m
 * @param width the width of the resulting image
 * @param height the height of the resulting image
 * @param bins the values for the chart
 * @param freqs the corresponding frequencies
 * @param summary the summary stats for the box plot
 * @param outliers an optional list of outliers for the box plot
 * @param additionalArgs optional arguments to the renderer (may be null)
 * @return a buffered image
 * @throws Exception if a problem occurs
 */
public static BufferedImage renderCombinedBoxPlotAndHistogramFromSummaryData(int width, int height,
        List<String> bins, List<Double> freqs, List<Double> summary, List<Double> outliers,
        List<String> additionalArgs) throws Exception {

    String plotTitle = "Combined Chart";
    String userTitle = getOption(additionalArgs, "-title");
    plotTitle = (userTitle != null) ? userTitle : plotTitle;

    List<String> opts = new ArrayList<String>();
    opts.add("-title=histogram");
    BufferedImage hist = renderHistogramFromSummaryData(width / 2, height, bins, freqs, opts);
    opts.clear();
    opts.add("-title=box plot");
    BufferedImage box = null;
    try {
        box = renderBoxPlotFromSummaryData(width / 2, height, summary, outliers, opts);
    } catch (Exception ex) {
        // if we can't generate the box plot (i.e. probably because
        // data is 100% missing) then just return the histogram
    }

    if (box == null) {
        width /= 2;
    }
    BufferedImage img = new BufferedImage(width, height + 20, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2d = img.createGraphics();
    g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_GASP);
    g2d.setFont(new Font("SansSerif", Font.BOLD, 12));
    g2d.setColor(Color.lightGray);
    g2d.fillRect(0, 0, width, height + 20);
    g2d.setColor(Color.black);
    FontMetrics fm = g2d.getFontMetrics();
    int fh = fm.getHeight();
    int sw = fm.stringWidth(plotTitle);

    if (box != null) {
        g2d.drawImage(box, 0, 20, null);
        g2d.drawImage(hist, width / 2 + 1, 20, null);
    } else {
        g2d.drawImage(hist, 0, 20, null);
    }
    g2d.drawString(plotTitle, width / 2 - sw / 2, fh + 2);
    g2d.dispose();

    return img;
}