我编写了一些代码来仅打印出您想要的字体名称,而不仅仅是打印出所有字体。
- (NSString *)realNameOfFont:(NSString *)fullFontName {
NSString *fontName = [[fullFontName componentsSeparatedByString:@"."] firstObject];
NSString *ext = [fullFontName pathExtension];
NSData *data = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:fontName ofType:ext]];
if (data == nil) {
NSLog(@"Failed to load font. Data at path %@ is null", fullFontName);
return nil;
}
CFErrorRef errorRef;
CGDataProviderRef provider = CGDataProviderCreateWithCFData((CFDataRef)data);
CGFontRef font = CGFontCreateWithDataProvider(provider);
NSString *realFontName = (__bridge NSString *)CGFontCopyPostScriptName(font);
if (!CTFontManagerRegisterGraphicsFont(font, &errorRef)) {
NSError *error = (__bridge NSError *)errorRef;
if (error.code != kCTFontManagerErrorAlreadyRegistered) {
NSLog(@"Failed to load font: %@", error);
}
}
NSLog(@"Real font name: %@", realFontName);
CFRelease(font);
CFRelease(provider);
return realFontName;
}
例子:
NSArray *fonts = @[@"bg_en_AmaticSC-Bold111.otf", @"bg_en_segoescb_0.ttf", @"bg_en_UTM Cookies_2.ttf", @"bg_en_VSCOProximaExtrabold_0.otf"];
for (NSString *fontFullName in fonts) {
[self realNameOfFont:fontFullName];
}
结果:
Failed to load font. Data at path bg_en_AmaticSC-Bold111.otf is null
Real font name: SegoeScript-Bold
Real font name: UTM-Cookies
Real font name: ProximaNova-Extrabld