1.导入字体文件
可以从网上下载,或者从MacOS中的字体集中导出,字体集的路径为/Library/Fonts,里面的字体可以直接添加到工程中使用
2.在Info.plist文件中添加导入的字体
添加Fonts provided by application字段,并添加要使用的字体,字体名称必须和导入到工程中的文件名相同,而且要写上后缀
3.检查Targets->Build Phases->Copy Bundle Resources中是否有导入的字体文件,如果没有的话重新导入一遍
4.代码实现
//导入头文件
#import <CoreText/CTFont.h>
#import <CoreText/CTFontManager.h>
//以下方法来获取字体
//获取字体数组,对于ttf文件,返回的数组中只有一个,ttc文件返回的数组中至少一个
-(NSArray*)customFontArrayWithPath:(NSString*)path size:(CGFloat)size
{
CFStringRef fontPath = CFStringCreateWithCString(NULL, [path UTF8String], kCFStringEncodingUTF8);
CFURLRef fontUrl = CFURLCreateWithFileSystemPath(NULL, fontPath, kCFURLPOSIXPathStyle, 0);
CFArrayRef fontArray = CTFontManagerCreateFontDescriptorsFromURL(fontUrl);
CTFontManagerRegisterFontsForURL(fontUrl, kCTFontManagerScopeNone, NULL);
NSMutableArray *customFontArray = [NSMutableArray array];
for (CFIndex i = 0 ; i < CFArrayGetCount(fontArray); i++){
CTFontDescriptorRef descriptor = CFArrayGetValueAtIndex(fontArray, i);
CTFontRef fontRef = CTFontCreateWithFontDescriptor(descriptor, size, NULL);
NSString *fontName = CFBridgingRelease(CTFontCopyName(fontRef, kCTFontPostScriptNameKey));
UIFont *font = [UIFont fontWithName:fontName size:size];
[customFontArray addObject:font];
}
return customFontArray;
}
//获取字体文件路径病使用字体
NSString * path = [[NSBundle mainBundle] pathForResource:@"Xingkai.ttc" ofType:nil];
NSArray * fontNames = [self customFontArrayWithPath:path size:20];
label.font = fontNames[0];