12

FontMetrics doesn't have getters for cap height and x-height of a font.

How can I obtain these values?

As far as cap height goes, there's no guarantee for a particular capital letter that the letter's ascent is the same as the cap height. (e.g. a capital H isn't guaranteed to be flat on the top)

As far as x height goes, I assume it's probably the same as the height of an "x", but again, there's no guarantee.


edit: Grr! I just tried FontMetrics.getBounds() and FontMetrics.getLineMetrics() for specific character sequences, and I always get the same answer for heights (getBounds() does differ for widths, obviously). There's a note in the hasUniformLineMetrics() method about a fontmetrics having several fonts to cover the character set, but that covers character groups, not individual characters.

Jason S
  • 184,598
  • 164
  • 608
  • 970
  • There is an interface `java.awt.font.OpenType` which could be used to retrieve font tables, and thus get the `x-height` defined by the font. However, that interface is not used apparently: http://stackoverflow.com/questions/33716004/how-do-i-use-the-opentype-interface-in-java – HRJ Nov 15 '15 at 04:45

4 Answers4

4

What you are looking for is the screen render box that tells you the exact size of text.

This means that you will need to supply information at some point about the surface you are drawing on and the string you are drawing. The reason is that the system simply does not know the visual result until late in rendering. I used:

Graphics2D g;
g.getFont().createGlyphVector(g.getFontRenderContext(),"abc").getVisualBounds();

You might also try:

Graphics2D g;
g.getFont().getMaxCharBounds(g.getFontRenderContext());

I too have trouble keeping all those font methods straight.

warren
  • 563
  • 2
  • 13
0

Well, if you're trying to make a box with text that fits the text, i think you can just make the height the font size itself

Im not sure, but i think that is what i've done in the past

jackcogdill
  • 4,900
  • 3
  • 30
  • 48
0

As for the x-height, the following code woks fine for me:

    public double getXHeight(Font font)
    {
        FontRenderContext fc = new FontRenderContext(null, false, false);
        TextLayout layout = new TextLayout("x", font, fc);
        return layout.getBounds().getHeight();
    }
radkovo
  • 868
  • 6
  • 10
  • 1
    Sorry to be pedantic, but the height of an "x" character is not necessarily the same as the x-height of a typeface. – Jason S Jul 10 '14 at 16:44
0

I've not worked with it, but the GlyphView.GlyphPainter class has getAscent, getDescent and getHeight methods. That might be something to check out.

Brad Mace
  • 27,194
  • 17
  • 102
  • 148