Java FontMetrics getStringImage(Font font, String... strs)

Here you can find the source of getStringImage(Font font, String... strs)

Description

get String Image

License

Open Source License

Declaration

public static BufferedImage getStringImage(Font font, String... strs) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.awt.*;
import java.awt.font.FontRenderContext;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;

import java.util.*;

public class Main {

    public static BufferedImage getStringImage(Font font, String... strs) {

        BufferedImage image = new BufferedImage(1, 1, 6);
        Graphics graphics = image.getGraphics();
        graphics.setFont(font);/*from w w  w.  j  ava2s.  c o m*/

        FontRenderContext fontRenderContext = graphics.getFontMetrics().getFontRenderContext();
        Rectangle2D rectangle2D = font.getStringBounds(getStringArrayMaxLengthString(strs), fontRenderContext);
        graphics.dispose();

        int width = (int) Math.ceil(rectangle2D.getWidth());
        int height = 0;

        for (int i = 0; i < strs.length; i++) {

            height += (int) Math.ceil(rectangle2D.getHeight());
        }
        return new BufferedImage(width, height, 6);
    }

    public static String getStringArrayMaxLengthString(String[] strs) {

        java.util.List<Integer> list = new ArrayList<>();
        Map<Integer, String> map = new HashMap<>();

        for (int i = 0; i < strs.length; i++) {

            list.add(strs[i].length());
            map.put(strs[i].length(), strs[i]);
        }
        Collections.sort(list);

        return map.get(list.get(list.size() - 1));
    }
}

Related

  1. getMaxFontHeight(final java.awt.Font font)
  2. getMonospacedFontNames()
  3. getMonospacedFontsFamillyName()
  4. getPrefSize(FontMetrics fm, String keyTip)
  5. getStringForMaxWidth(FontMetrics fm, String s, int maxWidth)
  6. getStringLengthInPixels(String s, Graphics g)
  7. getStringRect(Font f, String s)
  8. getTextCenterShear(final FontMetrics fm, final String text)
  9. getTextCenterShearX(final FontMetrics fm, final String text)