我有一个用于我的应用程序的字体,它只使用英文字符。我使用CoreText
来显示文本,我注意到每当有人输入一个未包含在字体中的字符(如阿拉伯字符)时,程序就会挂起来:
CTFramesetterCreateFrame(textFramesetter, CFRangeMake(0, 0), textMutablePath, NULL);
我有几个问题:
答案 0 :(得分:9)
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", FontContainsCharacter([UIFont fontWithName:@"Helvetica" size:12], 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
答案 1 :(得分:0)
我找到了第一个问题的答案,并基于Rob Mayoff在另一个问题中的回答:CTFontGetGlyphsForCharacters always returns false
- (BOOL) textExistsInFont:(NSString *)text
{
CTFontRef fontRef = CTFontCreateWithName((__bridge CFStringRef)self.fontName, self.fontSize, NULL);
NSUInteger count = text.length;
unichar characters[count];
[text getCharacters:characters range:NSMakeRange(0, count)];
CGGlyph glyphs[count];
if (CTFontGetGlyphsForCharacters(fontRef, characters, glyphs, count) == false)
{
return NO;
}
else
{
return YES;
}
}
我的第二个问题我仍在努力,但我得到的印象是Apple系统字体(Helvetica Neue)涵盖多种语言。但要验证。因此,如果字符不是您正在使用的字体,那么切换到系统字体可能是一个可行的选择。