如何测量给定字体类型和字体大小中最大字符的最大大小?

时间:2012-12-19 08:22:19

标签: ios fonts

我想缓存一些给定字体类型和字体大小的字符纹理,但我无法确定整个unicode字符集中最大字符可能占用的最大大小。

如何计算这个尺寸?

2 个答案:

答案 0 :(得分:-1)

您正在寻找的是Font Bounding Box(或BBox)。在iOS中,您需要一个CGFontRef,然后可以使用该函数:

CGRect CGFontGetFontBBox (
   CGFontRef font
);

返回字体边界框,它是字体中所有字形边界框的并集​​。它以字形单位返回值。

答案 1 :(得分:-1)

好吧,你可以使用sizeWithFont:

并检查最大(或最高或最大的区域)

它适用于宽度和面积,但似乎所有角色都有相同的高度,甚至点“。”

无论如何,我想这样的话应该回答你的问题:

UIFont* aFont = [UIFont fontWithName:@"HelveticaNeue" size:15];
NSString* charsToTest = @"abcdf...xyz, ABCD...XYZ, 0123...";
float maxArea = 0;
float maxWidth = 0;
float maxHeight = 0;
NSString* largerChar;
NSString* tallerChar;
NSString* biggerChar;
for (int i = 0; i<charsToTest.length; i++) {
    NSRange currentRange;
    currentRange.length = 1;
    currentRange.location = i;
    NSString* currentCharToTest = [charsToTest substringWithRange:currentRange];
    CGSize currentSize = [currentCharToTest sizeWithFont:aFont];
    if (currentSize.width > maxWidth) {
        maxWidth = currentSize.width;
        largerChar = currentCharToTest;
        NSLog(@"char:%@, new record width: %f", largerChar, maxWidth);
    }
    if (currentSize.height > maxHeight) {
        maxHeight = currentSize.height;
        tallerChar = currentCharToTest;
        NSLog(@"char:%@, new record height:%f", tallerChar, maxHeight);
    }
    float currentArea = currentSize.height * currentSize.width;
    if ( currentArea > maxArea) {
        maxArea = currentArea;
        biggerChar = currentCharToTest;
        NSLog(@"char:%@, new area record: %f", biggerChar, maxArea);
    }
}
// final resut:
NSLog(@"\n\n");
NSLog(@"char:%@ --> MAX WIDTH IS: %f", largerChar, maxWidth);
NSLog(@"char:%@ --> MAX HEIGHT IS: %f", tallerChar, maxHeight);
NSLog(@"char:%@ --> MAX AREA IS: %f\n\n", biggerChar, maxArea);