iOS中使用特殊字体

1.导入字体文件
可以从网上下载,或者从MacOS中的字体集中导出,字体集的路径为/Library/Fonts,里面的字体可以直接添加到工程中使用
这里写图片描述
2.在Info.plist文件中添加导入的字体
添加Fonts provided by application字段,并添加要使用的字体,字体名称必须和导入到工程中的文件名相同,而且要写上后缀
plist文件设置
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];

效果图

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Bright1st

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值