Measure dimensions of biggest character in a CGFon

2019-07-02 22:50发布

问题:

I am using CoreAnimation to build a view consisting of several layer which will be animated later on. There are also CATextLayers which will contain only one character of a given font in a given size. To make it pretty I would like to set the bounds of the layer so that the character fits in neatly.

The problem is that I have to determine the size of the biggest character in a CGFont which will be the basis of the bounds calculation for the text layer.

In this question on SO measure size of each character in a string it is explained how to get the size of each character. So one solution would be to iterate through the characters of the font and find out the biggest character.

However I have found the CGFontGetFontBBox function. The documentation says

Return Value

The bounding box of the font.

Discussion

The font bounding box is the union of all of the bounding boxes for all the glyphs in a >font. The value is specified in glyph space units.

This sounds to me that this is exactly what I want. One proble remains that I have to convert the glyph space units back to pixels. I tried it with the following code but it gives strange results:

/* calculate the bounding box of the biggest character in the font with a given
 * font size
 */
- (CGSize) boundingBoxForFont:(CGFontRef)aFont withSize:(CGFloat)aSize
{
    if (!aFont) {
        CFStringRef fontName = CFStringCreateWithCString(NULL, "Helvetica", CFStringGetSystemEncoding());
        aFont = CGFontCreateWithFontName(fontName);
        CFRelease(fontName);
    }
    CGRect bbox = CGFontGetFontBBox(aFont);
    int units = CGFontGetUnitsPerEm(aFont);
    CGFloat maxHeight = ( CGRectGetHeight(bbox) / (CGFloat) units ) * aSize;
    CGFloat maxWidth = ( CGRectGetWidth(bbox) / (CGFloat) units ) * aSize;
    return CGSizeMake(maxWidth, maxHeight);
}

It is strange that the CGRect bbox is wider than taller, which makes no sense to me as characters in a font are usually taller than wider, but maybe I am using it wrong.

Is there an alternative of how to use this function?

EDIT

Could it be the case that I am mixing up characters and glyphs? Could it be that the font contains a wide glyph which represents several characters?

回答1:

Yes, I think you are on the right track. For example, ligatures such as ffl count as a single glyph and are most likely wider than tall. Also, the em dash — is supposed to be as wide as the capital height.