Java font size from width

五迷三道 提交于 2019-12-07 10:46:56

问题


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.


回答1:


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);



回答2:


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;
}


来源:https://stackoverflow.com/questions/14380035/java-font-size-from-width

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!