Java Font Text Size getStringSize(String textToMeasure, Font displayFont)

Here you can find the source of getStringSize(String textToMeasure, Font displayFont)

Description

Measures the size of the input string, taking into account the current font and newlines.

License

BSD License

Declaration

public static Dimension getStringSize(String textToMeasure, Font displayFont) 

Method Source Code

//package com.java2s;
/**//  w  w  w  .j  av  a 2s.  c  o  m
 * Manipulate and analyze Strings.
 * 
 * <p>
 * <span class="BSDLicense"> This software is distributed under the <a
 * href="http://hci.stanford.edu/research/copyright.txt">BSD License</a>. </span>
 * </p>
 * 
 * @author <a href="http://graphics.stanford.edu/~ronyeh">Ron B Yeh</a> (ronyeh(AT)cs.stanford.edu)
 */

import java.awt.Dimension;
import java.awt.Font;
import java.awt.font.FontRenderContext;
import java.awt.geom.Rectangle2D;

public class Main {
    /**
     * Measures the size of the input string, taking into account the current font and newlines.
     * 
     * @return
     */
    public static Dimension getStringSize(String textToMeasure, Font displayFont) {
        final FontRenderContext fontRenderContext = new FontRenderContext(null, true, true);

        // break it up by lines (in case there are newlines "\n")
        final String[] strings = textToMeasure.split("\n");

        double totalHeight = 0;
        double maxWidth = 0;

        for (String s : strings) {
            Rectangle2D stringBounds = displayFont.getStringBounds(s, fontRenderContext);
            maxWidth = Math.max(maxWidth, stringBounds.getWidth());
            totalHeight += stringBounds.getHeight();
        }

        final Dimension dimension = new Dimension();
        dimension.setSize(maxWidth, totalHeight);
        return dimension;
    }
}

Related

  1. getStringDimension(Component comp, String str)
  2. getStringDimensions(Graphics2D graphics, Font font, String[] stringsByLine)
  3. getStringDisplaySize(String input)
  4. getStringSize(final Graphics g, final Font font, final String text)
  5. getStringSize(Graphics g, String text, Font font)
  6. getStringSizeForFont(final String string, final Font font)