Java: how do you find out the cap height and x-height of a font?
Asked Answered
F

4

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.

Fidelia answered 1/6, 2011 at 14:0 Comment(1)
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: #33716504Geesey
U
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.

Unstudied answered 6/5, 2012 at 6:58 Comment(0)
R
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.

Roadstead answered 18/6, 2011 at 5:51 Comment(1)
Ascent is usually larger that cap height.Guimond
T
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

Traveller answered 6/5, 2012 at 2:27 Comment(0)
H
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();
    }
Hedelman answered 10/7, 2014 at 12:10 Comment(1)
Sorry to be pedantic, but the height of an "x" character is not necessarily the same as the x-height of a typeface.Fidelia

© 2022 - 2024 — McMap. All rights reserved.