iOS 下載字體文件otf和ttf并使用

前提,設(shè)計師喜歡使用iOS系統(tǒng)原先沒有的字體類型來設(shè)計項目中的文字文案。把需要的otf和ttf的字體文件導(dǎo)入的項目中直接使用,網(wǎng)上也有很多例子,但是動不動一個字體文件就要10MB以上,顯得包體在應(yīng)用商場的大小會大了不少??梢源蜷_項目后再進行下載(神不知鬼不覺,哈哈哈)。

使用的第三方庫是AFNetworking、SSZipArchive。

JZFontStyleHelper.h文件
#import <Foundation/Foundation.h>
#import <AFNetworking/AFNetworking.h>
#import <CoreText/CoreText.h>
#import "SSZipArchive.h"

NS_ASSUME_NONNULL_BEGIN

@interface JZFontStyleHelper : NSObject

// 下載完成回調(diào)
@property (nonatomic , strong) void (^downloadFinishBlock)(NSString *path);
// 解壓完成回調(diào)
@property (nonatomic , strong) void (^matchFinishBlock)(void);
// 根據(jù)鏈接下載Zip包
- (void)downloadUrlFontWithUrl:(NSString *)fontUrl;
// 獲取下載后的文件名
- (NSString *)getCustomFontName;

@end

NS_ASSUME_NONNULL_END
JZFontStyleHelper.m文件
@implementation JZFontStyleHelper

- (void)downloadUrlFontWithUrl:(NSString *)fontUrl {
    
    if ([self checkUrlFontIsDownload]) {
        return;
    }
    
    // 下載字體文件
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
    
    NSURL *URL = [NSURL URLWithString:fontUrl];
    NSURLRequest *request = [NSURLRequest requestWithURL:URL];
    
    NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        //NSDocumentDirectory
        //NSLibraryDirectory
        //用上述兩個其中一個均可
        NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSLibraryDirectory
                                                                              inDomain:NSUserDomainMask
                                                                     appropriateForURL:nil
                                                                                create:NO
                                                                                 error:nil];
        return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];
        
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        NSString * createFilePath = [filePath path];
        NSLog(@"下載后的地址-%@",createFilePath);
        if (self.downloadFinishBlock) {
            self.downloadFinishBlock(createFilePath);
        }
        //下載完后是zip包,要解壓
        [self uSSZipArchiveWithFilePath:createFilePath];
    }];
    
    [downloadTask resume];
}

/**
 SSZipArchive解壓
@param path 壓縮包文件路徑
 */
-(void)uSSZipArchiveWithFilePath:(NSString *)path
{
    // Caches路徑
    NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];
    // 解壓目標(biāo)路徑(自定義)
    NSString *destinationPath =[cachesPath stringByAppendingPathComponent:@"JZFontStyle"];
    // 解壓
    BOOL isSuccess = [SSZipArchive unzipFileAtPath:path toDestination:destinationPath];
    // 如果解壓成功則獲取解壓后文件列表
    if (isSuccess) {
        [self obtainZipSubsetWithFilePath:destinationPath];
        //解壓完后把zip文件包刪除掉
        NSFileManager *fileManager = [NSFileManager defaultManager];
        BOOL isDelete = [fileManager removeItemAtPath:path error:nil];
        NSLog(@"%@",isDelete ? @"刪除成功" : @"刪除失敗");
        if (self.matchFinishBlock) {
            self.matchFinishBlock();
        }
    }
}

/**
 獲取解壓后文件列表
 @param path 解壓后的文件路徑
 */
- (void)obtainZipSubsetWithFilePath:(NSString *)path
{
    NSString * destinationPath = path;
    // 讀取文件夾內(nèi)容
    NSError * error = nil;
    NSMutableArray * items = [[[NSFileManager defaultManager]
                             contentsOfDirectoryAtPath:destinationPath
                             error:&error] mutableCopy];
    if (error) {
        NSLog(@"error:%@",error.description);
        return;
    }
    // 解壓成功后該文件夾下的文件
    for (NSString * item_str in items) {
        NSLog(@"文件名:%@",item_str);
    }
}

// 判斷字體文件是否下載了
- (BOOL)checkUrlFontIsDownload {
    // Caches路徑
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];
    // 解壓目標(biāo)路徑(自定義)
    NSString * filePath = [path stringByAppendingPathComponent:@"JZFontStyle"];
    // 讀取文件夾內(nèi)容
    NSError * error = nil;
    NSMutableArray * items = [[[NSFileManager defaultManager]
                             contentsOfDirectoryAtPath:filePath
                             error:&error] mutableCopy];
    // 注冊字體
    for (NSString * item_str in items) {
        NSString * destinationPath = [filePath stringByAppendingPathComponent:item_str];
        NSString * fontName = [self registerCustomFontWithPath:destinationPath];
        NSLog(@"%@",fontName);
    }
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:filePath] && items.count > 0) {
        return YES;
    } else {
        return NO;
    }
}

// 根據(jù)下載解壓后的路徑來注冊字體
- (NSString *)registerCustomFontWithPath:(NSString*)path {
    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));
    CGFontRelease(fontRef);
    return fontName;
}

- (NSString *)getCustomFontName {
    // Caches路徑
    NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];
    // 解壓目標(biāo)路徑
    NSString *fontStylePath =[cachesPath stringByAppendingPathComponent:@"JZFontStyle"];
    
    // 讀取文件夾內(nèi)容
    NSError *error = nil;
    NSMutableArray*items = [[[NSFileManager defaultManager]
                             contentsOfDirectoryAtPath:fontStylePath
                             error:&error] mutableCopy];
    
    if (items.count == 0) return @"";
    // 獲取文件夾下第一個字體文件
    NSString * fontName_str = items.firstObject;
    NSString *destinationPath =[fontStylePath stringByAppendingPathComponent:fontName_str];
    
    NSString * fontName = [self registerCustomFontWithPath:destinationPath];
    
    return fontName;
}

@end

下載和使用
- (void)viewDidLoad {
    [super viewDidLoad];

    JZFontStyleHelper * fontStyleHelper = [[JZFontStyleHelper alloc] init];
    NSString * fontUrl = @"";//字體文件下載鏈接
    [fontStyleHelper downloadUrlFontWithUrl:fontUrl];
    /**
     https://xxx/font_style1.zip
     我下載有兩個字體
     文件名:SourceHanSerifCN-Bold.otf
     文件名:SourceHanSerifCN-Heavy.otf
     */
    // 知道文件名直接使用
    self.label.font = [UIFont fontWithName:@"SourceHanSerifCN-Bold" size:24];
    
    // 也可以解壓后使用
    __weak typeof (self) weakSelf = self;
    [fontStyleHelper setMatchFinishBlock:^{
        weakSelf.label.font = [UIFont fontWithName:@"SourceHanSerifCN-Bold" size:24];
    }];
    
    // 可以獲取解壓后文件地址的字體
    NSString * fontName = [fontStyleHelper getCustomFontName];
    self.label.font = [UIFont fontWithName:fontName size:24];
}

- (UILabel *)label{
    if (!_label) {
        _label = [[UILabel alloc] init];
        _label.textColor = UIColor.blackColor;
        _label.text = @"自定義字體";
        _label.frame = CGRectMake(100, 100, 200, 100);
        [self.view addSubview:_label];
    }
    return _label;
}

直接下載.otf或者.ttf文件也可以,少了解壓步驟,在這里就不訴述了,大同小異。

參考資料:
IOS下載在線字體和系統(tǒng)字體
iOS解壓ZIP壓縮包

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容