2

I have a Font object and I need both the width and height of the font. I know that the getSize() returns the height of the font as the point-size of a font is generally the height, but I'm at a loss when it comes to determining the width of the font.

Alternatively, being able to determine the width of each specific character supported by the Font would also be an acceptable solution.

My best guess is that the width is specified when using the loadFont method, but the documentation does not specify whether the size parameter represents the width or the height of the font.

All fonts being used are mono-space fonts such as DejaVu Sans Mono, GNU FreeMono, and Lucida Sans Unicode.

  • The width of a single char depends on the graphics context you want to use your font in. If you want to use your font for a text string this could be helpful: [How to calculate the pixel width of a String in javaFX](http://stackoverflow.com/q/13015698/7274990) – Calculator Dec 26 '16 at 21:41
  • Also see related: [JavaFX FontMetrics](http://stackoverflow.com/questions/32237048/javafx-fontmetrics) – jewelsea Dec 28 '16 at 06:24

2 Answers2

4

I have run into the same problem, and there seems to be no easy way. My solution was to create a Text element with the correct font and check it's size:

double computeTextWidth(Font font, String text, double wrappingWidth) {
    Text helper = new Text();
    helper.setFont(font);
    helper.setText(text);
    // Note that the wrapping width needs to be set to zero before
    // getting the text's real preferred width.
    helper.setWrappingWidth(0);
    helper.setLineSpacing(0);
    double w = Math.min(helper.prefWidth(-1), wrappingWidth);
    helper.setWrappingWidth((int)Math.ceil(w));
    double textWidth = Math.ceil(helper.getLayoutBounds().getWidth());
    return textWidth;
}

If I remember correctly the trick here is to set prefWidth to -1. See the JavaDoc.

hotzst
  • 7,238
  • 9
  • 41
  • 64
0
FontMetrics metrics = Toolkit.getToolkit().getFontLoader().getFontMetrics(font);
float charWidth = metrics.computeStringWidth("a");
float charHeight = metrics.getLineHeight();
sirolf2009
  • 819
  • 8
  • 15