iOS下载使用自定义字体

使用内置字体就不说了,这里说一下如何下载并使用自定义的字体
第一步,下载字体
首先得要下载ttf文件,下面代码中的dict为

{
    id = 23eb3318ae46465f8ffe52e74fb68751;
    name = "\U534e\U5eb7\U53ef\U7231\U82f1\U6587\U4f53";
    url = "font/2017/04/19/90f8f66d94fe43578bd477700c6de98a.ttf";
}

则URL应为:http://www.zume100.com:8091/app/font/downloadFont?id=23eb3318ae46465f8ffe52e74fb68751
下载时要导入第三方库#import "AFNetworking.h"

  NSString * url = [NSString stringWithFormat:@"%@/font/downloadFont?id=%@",[ZumeSysConfig getServerUrl],[dict objectForKey:@"id"]];
  NSURL * URL = [NSURL URLWithString:url];
  NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
  AFURLSessionManager * manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
  NSURLRequest *request = [NSURLRequest requestWithURL:URL];
  NSURLSessionDownloadTask *_downloadTask;
  _downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
                    NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
                    NSString * str = [dict objectForKey:@"name"];
                    NSString *path = [cachesPath stringByAppendingPathComponent:str];
                    return [NSURL fileURLWithPath:path];
                } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
                    NSString *imgFilePath = [filePath path];
                }];
                    [_downloadTask resume];
            }

下载完成,文件地址是imgFilePath
第二部,使用ttf

 NSString *imgFilePath = [filePath path];
 NSURL *fontUrl = [NSURL fileURLWithPath:imgFilePath];
 CGDataProviderRef fontDataProvider =  CGDataProviderCreateWithURL((__bridge CFURLRef)fontUrl);
 CGFontRef fontRef = CGFontCreateWithDataProvider(fontDataProvider);
 CGDataProviderRelease(fontDataProvider);
 CTFontManagerRegisterGraphicsFont(fontRef, NULL);
 NSString *fontName = CFBridgingRelease(CGFontCopyPostScriptName(fontRef));
 label.font = [UIFont fontWithName:fontName size:24];

上面的fontName就是对应下载ttf文件的字体,这样就能直接使用了

你可能感兴趣的:(iOS下载使用自定义字体)