Measure dimensions of biggest character in a CGFont

谁说我不能喝 提交于 2019-12-23 16:55:06

问题


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.



来源:https://stackoverflow.com/questions/10437567/measure-dimensions-of-biggest-character-in-a-cgfont

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!