简体   繁体   中英

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

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. (eg 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.

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.

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM