18

我已经多次看到这个问题被问和回答过,但我还没有看到真正的答案。常见的“解决方案”是:

  • 将字体添加到应用程序包中并将其注册到 info.plist 文件中。
  • 使用自定义字体解析和渲染库(如 Zynga 的FontLabel)。
  • 这是不可能的。

那么问题来了: iOS下如何动态加载字体? “动态”加载字体意味着加载在应用程序编译时未知的任何给定字体。

4

6 回答 6

25

可以轻松地从任何位置或任何字节流动态加载字体。请参阅此处的文章:http: //www.marco.org/2012/12/21/ios-dynamic-font-loading

NSData *inData = /* your font-file data */;
CFErrorRef error;
CGDataProviderRef provider = CGDataProviderCreateWithCFData((CFDataRef)inData);
CGFontRef font = CGFontCreateWithDataProvider(provider);
if (! CTFontManagerRegisterGraphicsFont(font, &error)) {
    CFStringRef errorDescription = CFErrorCopyDescription(error)
    NSLog(@"Failed to load font: %@", errorDescription);
    CFRelease(errorDescription);
}
CFRelease(font);
CFRelease(provider);
  • 您不必将字体放入捆绑包中。
  • 您不必在 info.plist 中显式注册字体。

另请参阅: https ://developer.apple.com/library/mac/#documentation/Carbon/Reference/CoreText_FontManager_Ref/Reference/reference.html#//apple_ref/doc/uid/TP40008278

https://developer.apple.com/library/mac/#documentation/GraphicsImaging/Reference/CGFont/Reference/reference.html#//apple_ref/c/func/CGFontCreateWithDataProvider

于 2012-12-27T02:07:25.493 回答
9

Marco 最近发表了一篇题为动态加载 iOS 字体的帖子的好时机。

NSData *inData = /* your decrypted font-file data */;
CFErrorRef error;
CGDataProviderRef provider = CGDataProviderCreateWithCFData((CFDataRef)inData);
CGFontRef font = CGFontCreateWithDataProvider(provider);
if (! CTFontManagerRegisterGraphicsFont(font, &error)) {
    CFStringRef errorDescription = CFErrorCopyDescription(error)
    NSLog(@"Failed to load font: %@", errorDescription);
    CFRelease(errorDescription);
}
CFRelease(font);
CFRelease(provider);
于 2012-12-27T04:01:46.930 回答
2
// Note : add "CoreText.framework" into your project to support following code

// Put loadCustomFont function inside app delegate or any shared class to access any where in code...

    -(void)loadCustomFont:(NSMutableArray *)customFontFilePaths{

        for(NSString *fontFilePath in customFontFilePaths){

            if([[NSFileManager defaultManager] fileExistsAtPath:fontFilePath]){

                NSData *inData = [NSData dataWithContentsOfFile:fontFilePath];
                CFErrorRef error;
                CGDataProviderRef provider = CGDataProviderCreateWithCFData((__bridge CFDataRef)inData);
                CGFontRef font = CGFontCreateWithDataProvider(provider);
                // NSString *fontName = (__bridge NSString *)CGFontCopyFullName(font);
                if (!CTFontManagerRegisterGraphicsFont(font, &error)) {
                    CFStringRef errorDescription = CFErrorCopyDescription(error);
                    NSLog(@"Failed to load font: %@", errorDescription);
                    CFRelease(errorDescription);
                }
                CFRelease(font);
                CFRelease(provider);
            }
        }
    }

    // Use as follow inside your view controller...

    - (void)viewDidLoad
    {
        [super viewDidLoad];

        // pass all font files name into array which you want to load dynamically...
        NSMutableArray *customFontsPath = [[NSMutableArray alloc] init];
        NSArray *fontFileNameArray = [NSArray arrayWithObjects:@"elbow_v001.ttf",@"GothamRnd-MedItal.otf", nil];

        for(NSString *fontFileName in fontFileNameArray){

            NSString *fileName = [fontFileName stringByDeletingPathExtension];
            NSString *fileExtension = [fontFileName pathExtension];
            [customFontsPath addObject:[[NSBundle mainBundle] pathForResource:fileName ofType:fileExtension]];
        }


        AppDelegate *appDel = (AppDelegate *)[[UIApplication sharedApplication] delegate];
        // load custom font into memory...
        [appDel loadCustomFont:customFontsPath];

        // Use font as below
        [lblName setFont:[UIFont fontWithName:@"Elbow v100" size:15.0]];
        [lblName2 setFont:[UIFont fontWithName:@"Gotham Rounded" size:20.0]];
    }
于 2013-05-07T06:49:34.050 回答
2

从服务器下载 TTF 文件?

如果您正在下载 TTF 文件,那么您可以执行以下操作以使用 iOS 字体管理器注册您的自定义字体,这段代码还负责 TTF 文件更新(字体更新):

+(void)registerFontsAtPath:(NSString *)ttfFilePath
{
    NSFileManager * fileManager = [NSFileManager defaultManager];

    if ([fileManager fileExistsAtPath:ttfFilePath] == YES)
    {
        [UIFont familyNames];//This is here for a bug where font registration API hangs for forever.

        //In case of TTF file update : Fonts are already registered, first de-register them from Font Manager
        CFErrorRef cfDe_RegisterError;
       bool fontsDeregistered = CTFontManagerUnregisterFontsForURL((__bridge CFURLRef)[NSURL fileURLWithPath:ttfFilePath], kCTFontManagerScopeNone, &cfDe_RegisterError);


        //finally register the fonts with Font Manager,
        CFErrorRef cfRegisterError;
        bool fontsRegistered= CTFontManagerRegisterFontsForURL((__bridge CFURLRef)[NSURL fileURLWithPath:ttfFilePath], kCTFontManagerScopeNone, &cfRegisterError);
}
于 2017-01-07T17:00:27.557 回答
2

这是 Swift 3 的 @mt81 的更新答案:

guard
    let path = "Path to some font file",
    let fontFile = NSData(contentsOfFile: path)
else {
    print "Font file not found?"
}

guard let provider = CGDataProvider(data: fontFile)
else {
    print "Failed to create DataProvider"
}

let font = CGFont(provider)
let error: UnsafeMutablePointer<Unmanaged<CFError>?>? = nil

guard CTFontManagerRegisterGraphicsFont(font, error) else {
    guard
        let unError = error?.pointee?.takeUnretainedValue(),
        let description = CFErrorCopyDescription(unError)
    else {
        print "Unknown error"
    }
    print description
}
于 2017-09-04T13:32:03.750 回答
0

这里是快速版本:

let inData: NSData = /* your font-file data */;
let error: UnsafeMutablePointer<Unmanaged<CFError>?> = nil
let provider = CGDataProviderCreateWithCFData(inData)
if let font = CGFontCreateWithDataProvider(provider) {
    if (!CTFontManagerRegisterGraphicsFont(font, error)) {
        if let unmanagedError = error.memory {
            let errorDescription = CFErrorCopyDescription(unmanagedError.takeUnretainedValue())
            NSLog("Failed to load font: \(errorDescription)");
        }
    }
}
于 2016-03-30T11:48:43.287 回答