如何检查字体是否支持字符

时间:2014-04-17 14:33:43

标签: ios objective-c fonts uifont emoji

我正在处理带有文本字段的应用。在这个字段中写的文本将被打印,我有一些问题,如表情符号,中文字符等...因为字体不提供这些字符。

这就是为什么我想获得字体提供的所有字符(下载字体以便我可以直接处理文件或使用UIFont对象)。

我听说过CTFontGetGlyphsForCharacters,但我不确定这个功能是否符合我的要求,而且无法让它发挥作用。

这是我的代码:

CTFontRef fontRef = CTFontCreateWithName((CFStringRef)font.fontName, font.pointSize, NULL);
NSString *characters = @""; // emoji character
NSUInteger count = characters.length;
CGGlyph glyphs[count];
if (CTFontGetGlyphsForCharacters(fontRef, (const unichar*)[characters cStringUsingEncoding:NSUTF8StringEncoding], glyphs, count) == false)
    NSLog(@"CTFontGetGlyphsForCharacters failed.");

此处CTFontGetGlyphsForCharacters返回 false 。它是我想要的,因为角色''所用字体不提供 问题是当我将NSString *characters = @""替换为NSString *characters = @"abc"时,CTFontGetGlyphsForCharacters再次返回 false 。显然,我的字体为所有ASCII字符提供了一个字形。

1 个答案:

答案 0 :(得分:7)

我终于解决了它:

- (BOOL)isCharacter:(unichar)character supportedByFont:(UIFont *)aFont
{
    UniChar characters[] = { character };
    CGGlyph glyphs[1] = { };
    CTFontRef ctFont = CTFontCreateWithName((CFStringRef)aFont.fontName, aFont.pointSize, NULL);
    BOOL ret = CTFontGetGlyphsForCharacters(ctFont, characters, glyphs, 1);
    CFRelease(ctFont);
    return ret;
}