Java Font Text Width shrinkFontForWidth(Font base, String text, int desiredWidth, Graphics getMetrics)

Here you can find the source of shrinkFontForWidth(Font base, String text, int desiredWidth, Graphics getMetrics)

Description

Finds the smallest font size that will fit a string within a given width.

License

Open Source License

Parameter

Parameter Description
base the base font which should be shrunk (not modified)
text the string to fit within the given width
desiredWidth the maximum possible width of the text, in pixels
getMetrics a Graphics object which should be used to obtain FontMetrics for the given font

Return

a Font identical to base except possibly with a different font size as above

Declaration

public static Font shrinkFontForWidth(Font base, String text, int desiredWidth, Graphics getMetrics) 

Method Source Code


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

import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;

public class Main {
    /**/*from   w w w.java2  s.c  o m*/
     * Finds the smallest font size that will fit a string within a given width.
     * 
     * <p>
     * Specifically, returns a {@link Font} <code>ret</code> with a size less than its current size such that <code>getMetrics.getFontMetrics(ret).stringWidth(text) &lt;= desiredWidth</code>.
     * </p>
     * 
     * @param base the base font which should be shrunk (not modified)
     * @param text the string to fit within the given width
     * @param desiredWidth the maximum possible width of the text, in pixels
     * @param getMetrics a {@link Graphics} object which should be used to obtain {@link FontMetrics} for the given font
     * @return a Font identical to <code>base</code> except possibly with a different font size as above
     */
    public static Font shrinkFontForWidth(Font base, String text, int desiredWidth, Graphics getMetrics) {
        FontMetrics metrics = getMetrics.getFontMetrics(base);
        while (metrics.stringWidth(text) > desiredWidth) {
            base = base.deriveFont((float) base.getSize() - 1);
        }
        return base;
    }
}

Related

  1. getTextWidth(String text, Graphics g, String newLineSplit)
  2. getWidth(String s, Graphics g)
  3. getWidthForText(String txt, Font font)
  4. getWidthOfDots(FontMetrics fontMetrics)
  5. setFixedWidthFont(Component comp)
  6. stringPixelWidth(String text, FontMetrics fm)
  7. stringWidth(final FontMetrics fm, final String string)
  8. stringWidth(Graphics g, String s)
  9. stringWidth(Graphics2D g, String s)