主要分为两步,第一步首先要对字体进行本地注册,执行如下代码
- (void)loadExternFonts:(NSString *)fontFilePath {
NSArray *availableFonts = [[NSFontManager sharedFontManager] availableFonts];
NSURL *fontURL = [NSURL fileURLWithPath:fontFilePath];
CFErrorRef error = NULL;
if (!CTFontManagerRegisterFontsForURL((__bridge CFURLRef)fontURL, kCTFontManagerScopeProcess, &error))
{
CFShow(error);
NSLog(@"register font failed %@",error);
}
else {
NSLog(@"register font success");
}
}
第二步,获取字库的名称,并进行加载
-(NSFont *)customFontWithPath:(NSString*)path size:(CGFloat)size {
NSURL *fontUrl = [NSURL fileURLWithPath:path];
CGDataProviderRef fontDataProvider = CGDataProviderCreateWithURL((__bridge CFURLRef)fontUrl);
CGFontRef fontRef = CGFontCreateWithDataProvider(fontDataProvider);
CGDataProviderRelease(fontDataProvider);
CTFontManagerRegisterGraphicsFont(fontRef, NULL);
NSString *fontName = CFBridgingRelease(CGFontCopyPostScriptName(fontRef));
NSFont *font = [NSFont fontWithName:fontName size:size];
CGFontRelease(fontRef);
return font;
}