使用 Objective - C 的字体文件 ( .ttf ) 的 PostScript 名称,并非所有已安装的字体

PostScript Name of a font file ( .ttf ) using Objective - C and not all installed fonts

我想找出已复制到文档目录的 .ttf 文件的 PostScript 名称...这样我就可以在不更改 .plist 文件的情况下以编程方式将字体设置为标签。

我知道这个代码:

  for (NSString *fontFamilyName in [UIFont familyNames]) {
    for (NSString *fontName in [UIFont fontNamesForFamilyName:fontFamilyName]) {
        NSLog(@"Family: %@    Font: %@", fontFamilyName, fontName);
    }
}

但我只想为一个文件示例查找 PostScript 名称:segoe.ttf

显然会有不同的字体文件将被复制到文档目录,我想只为每个文件获取 PostScript 名称,而不是像上面提到的代码中的那样。谢谢...

所以我用这段代码得到了它:

- (NSString *)realNameOfFont:(NSString *)fullFontName {

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NSString *documentsDirectory = [paths objectAtIndex:0];

NSString *docFilePath = [documentsDirectory stringByAppendingPathComponent:fullFontName];

NSData *data = [NSData dataWithContentsOfFile:docFilePath];
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(@"PostScript Font Name:%@", realFontName);
    CFRelease(font);
    CFRelease(provider);
    return realFontName;