我有一个字体,我用于我的应用程序,只使用英文字符.我使用CoreText来显示文本,我注意到只要有人输入了字体中没有包含的字符(比如阿拉伯字符),程序就会挂起来:
CTFramesetterCreateFrame(textFramesetter,CFRangeMake(0,0),textMutablePath,NULL);
我有一些问题:
>是否可以知道字体中是否包含某个字符?
>系统是否可以找到包含未知字符的字体?
解决方法
1)是否可以知道字体中是否包含某个字符?
BOOL FontContainsCharacter(UIFont *font,unichar character) { NSCharacterSet *characterSet = [font.fontDescriptor objectForKey:UIFontDescriptorCharacterSetAttribute]; return [characterSet characterIsMember:character]; }
2)系统是否可以找到包含未知字符的字体?
NSArray *FontDescriptorsForFontsContainingCharactersInString(NSString *string) { NSCharacterSet *characterSet = [NSCharacterSet characterSetWithCharactersInString:string]; NSDictionary *fontAttributes = @{UIFontDescriptorCharacterSetAttribute:characterSet}; UIFontDescriptor *fontDescriptor = [UIFontDescriptor fontDescriptorWithFontAttributes:fontAttributes]; return [fontDescriptor matchingFontDescriptorsWithMandatoryKeys:nil]; }
例如:
NSLog(@"%d",FontContainsCharacter([UIFont fontWithName:@"Helvetica" size:12],0x0041)); // "A" NSLog(@"%d",0x4F60)); // "你" for (UIFontDescriptor *fontDescriptor in FontDescriptorsForFontsContainingCharactersInString(@"你好")) { NSLog(@"%@",[UIFont fontWithDescriptor:fontDescriptor size:12].fontName); }
输出:
1 0 STHeitiSC-Light STHeitiSC-Medium STHeitiTC-Light STHeitiTC-Medium HiraKakuProN-W3 HiraKakuProN-W6 HiraMinProN-W3 HiraMinProN-W6