jules
jules

Reputation: 75

Java font size from width

I'm looking for a way to infer a Java AWT Font size from a width. For example, I know I want to write 'hello world' within 100 pixels. I know I'm using the font "Times", in style Font.PLAIN, and I want to get the font size that fits the best with my given width of 100 pixels.

I know I could calculate it in a loop (something like while(font.getSize() < panel.getWidth()), but to be honest I don't find it very elegant.

Upvotes: 5

Views: 5706

Answers (2)

jarnbjo
jarnbjo

Reputation: 34313

You can get the rendered width and height of a string using the FontMetrics class (be sure to enable fractional font metrics in the Graphics2D instance to avoid rounding errors):

Graphics2D g = ...;
g.setRenderingHint(
    RenderingHints.KEY_FRACTIONALMETRICS, 
    RenderingHints.VALUE_FRACTIONALMETRICS_ON);

Font font = Font.decode("Times New Roman");

String text = "Foo";

Rectangle2D r2d = g.getFontMetrics(font).getStringBounds(text, g);

Now, when you have the width of the text using a font with the default (or actually any) size, you can scale the font, so that the text will fit within a specified width, e.g. 100px:

font = font.deriveFont((float)(font.getSize2D() * 100/r2d.getWidth()));

Similarly, you may have to limit the font size, so that you don't exceed the available panel height.

To improve the appearance of the rendered text, you should also consider enabling antialiasing for text rendering and/or kerning support in the font:

g.setRenderingHint(
    RenderingHints.KEY_TEXT_ANTIALIASING, 
    RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

Map<TextAttribute, Object> atts = new HashMap<TextAttribute, Object>();
atts.put(TextAttribute.KERNING, TextAttribute.KERNING_ON);
font = font.deriveFont(atts);

Upvotes: 6

Nikolay Kuznetsov
Nikolay Kuznetsov

Reputation: 9579

Have a look at these two methods I am using. It is not elegant as you say, but it works.

private static int pickOptimalFontSize (Graphics2D g, String title, int width, int height) {
    Rectangle2D rect = null;

    int fontSize = 30; //initial value
    do {
        fontSize--;
        Font font = Font("Arial", Font.PLAIN, fontSize);
        rect = getStringBoundsRectangle2D(g, title, font);
    } while (rect.getWidth() >= width || rect.getHeight() >= height);

    return fontSize;
}

public static Rectangle2D getStringBoundsRectangle2D (Graphics g, String title, Font font) {
    g.setFont(font);
    FontMetrics fm = g.getFontMetrics();
    Rectangle2D rect = fm.getStringBounds(title, g);
    return rect;
}

Upvotes: 1

Related Questions