簡體   English   中英

如何在iOS下動態加載字體。 (真的)

[英]How to dynamically load a font under iOS. (for real)

我已經看過這個問題並且多次回答,但我沒有看到真正的答案。 常見的“解決方案”是:

  • 將字體添加到應用程序包並將其注冊到info.plist文件中。
  • 使用自定義字體解析和渲染庫(如Zynga的FontLabel )。
  • 它無法完成。

所以問題是: 如何在iOS下動態加載字體? “動態”加載字體意味着加載在應用程序編譯時未知的任何給定字體。

可以從任何位置或任何字節流輕松地動態加載字體。 請參閱此處的文章: 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

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);
// 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]];
    }

從服務器下載TTF文件?

如果您正在下載TTF文件,那么您可以使用iOS Font Manager注冊自定義字體,這段代碼也會處理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);
}

這里的swift版本:

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)");
        }
    }
}

以下是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
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM