Can I embed a custom font in a bundle and access it from an ios framework?

后端 未结 7 1319
北荒
北荒 2020-12-13 02:35

I\'m creating an ios framework with its bundle for packaging ressources (nib, images, fonts) and I\'m trying to embed a custom font

7条回答
  •  甜味超标
    2020-12-13 03:10

    Here is way I implemented it for my fmk based on the solution provided by "David M." This solution doesn't require to add the reference to the font in the plist.

    1) Class that load the font

    - (void) loadMyCustomFont{
        NSString *fontPath = [[NSBundle frameworkBundle] pathForResource:@"MyFontFileNameWithoutExtension" ofType:@"ttf"];
        NSData *inData = [NSData dataWithContentsOfFile:fontPath];
        CFErrorRef error;
        CGDataProviderRef provider = CGDataProviderCreateWithCFData((__bridge 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);
    }
    

    2) Category on NSBundle to get access to my bundle

    + (NSBundle *)frameworkBundle {
        static NSBundle* frameworkBundle = nil;
        static dispatch_once_t predicate;
        dispatch_once(&predicate, ^{
            NSString* mainBundlePath = [[NSBundle mainBundle] resourcePath];
            NSString* frameworkBundlePath = [mainBundlePath stringByAppendingPathComponent:@"MyBundleName.bundle"];
            frameworkBundle = [NSBundle bundleWithPath:frameworkBundlePath];
        });
        return frameworkBundle;
    }
    

    Note: require to integrate CoreText in your project

提交回复
热议问题