iOS 使用第三方字體


前言

在iOS的項目開發中經常遇到需要使用一些自定義的字體文件,比如仿宋_GB2312華康少女體等。之前我們為了使用這些自定義的字體,在應用的資源包中放入這些字體文件。因為字體文件通常比較大,有的一個字庫就達到10M以上,這樣打包后的ipa文件的體積就可能會變得很大,對於只有個別的模塊需要特殊的字體樣式的應用來說很不划算,那么在iOS6.0以后蘋果就開放了動態加載字體的權限。下面就iOS中使用字體的這兩種方式進行介紹。

使用靜態字體

將字體文件拷貝到項目工程中,在Info.plist文件中添加Fonts provided by application的配置項,其中每一個Item對應的是字體文件的名稱,如huakangshaonv.ttf

 

fontDemo ScreenShot.png

然后就可以調用+ (UIFont *)fontWithName:(NSString *)fontName size:(CGFloat)fontSize使用字體,如果不知道fontName可以遍歷打印出來:

- (void)allFont
{
    NSArray *fontFamilies = [UIFont familyNames];
    for (NSString *fontFamily in fontFamilies)
    {
        NSArray *fontNames = [UIFont fontNamesForFamilyName:fontFamily];
        NSLog (@">>> fontFamily : %@ , fontNames : %@", fontFamily, fontNames);
    }
}

使用動態字體

在網易新聞iOS客戶端中可以使用自定義的字體,對於未下載的字體可先下載然后安裝下次就能自動設置為該字體,效果如下:

 

 


 

wangyiFont.png

下面就該功能簡單介紹實現的步驟

  • 下載字體文件
- (NSString *)downloadZipFile:(NSString *)fileUrl toPath:(NSString *)path
{
    NSError *error = nil;
    NSURL *url = [NSURL URLWithString:fileUrl];
    NSString *fileName = [url lastPathComponent];
    NSData *data = [NSData dataWithContentsOfURL:url options:0 error:&error];
    if(!error)
    {
        NSString *zipPath = [path stringByAppendingPathComponent:fileName];
        [data writeToFile:zipPath options:0 error:&error];
        if(!error)
        {
            return zipPath;
        }
    }
    return nil;
}
  • 解壓zip壓縮包

iOS中解壓zip壓縮文件非常方便,使用ZipArchive這個開源項目按照如下的方式即可快速解壓zip文件。

- (NSString *)expandZipFile:(NSString *)src toPath:(NSString *)desc
{
    ZipArchive *za = [[ZipArchive alloc] init];
    if ([za UnzipOpenFile:src])
    {
        BOOL ret = [za UnzipFileTo:desc overWrite:YES];//解壓文件
        if(ret)
        {
            NSString *zipName = [src lastPathComponent];//獲取zip文件的文件名
            [[NSFileManager defaultManager] removeItemAtPath:zipPath error:nil];//刪除zip壓縮包
            zipName = [zipName substringToIndex:[zipName rangeOfString:@".zip"].location];//獲取解壓到的文件夾
            return [self.downloadPath stringByAppendingPathComponent:zipName];
        }
    }
    return nil;
}
  • 注冊指定路徑下的字體文件

下載回來的字體文件如果不做處理是不能直接使用的,使用前需要先注冊然后才能使用,注冊方式如下:

- (void)registerFont:(NSString *)fontPath
{
    NSData *dynamicFontData = [NSData dataWithContentsOfFile:fontPath];
    if (!dynamicFontData)
    {
        return;
    }
    CFErrorRef error;
    CGDataProviderRef providerRef = CGDataProviderCreateWithCFData((__bridge CFDataRef)dynamicFontData);
    CGFontRef font = CGFontCreateWithDataProvider(providerRef);
    if (! CTFontManagerRegisterGraphicsFont(font, &error))
    {
        //注冊失敗
        CFStringRef errorDescription = CFErrorCopyDescription(error);
        NSLog(@"Failed to load font: %@", errorDescription);
        CFRelease(errorDescription);
    }
    CFRelease(font);
    CFRelease(providerRef);
}

需要先引入#import <CoreText/CoreText.h>CoreText框架

  • 判斷字體是否加載

在使用字體文件前最好是先判斷字體是否已經被加載過了,判斷方式如下:

- (BOOL)isFontDownloaded:(NSString *)fontName
{
    UIFont* aFont = [UIFont fontWithName:fontName size:12.0];
    BOOL isDownloaded = (aFont && ([aFont.fontName compare:fontName] == NSOrderedSame || [aFont.familyName compare:fontName] == NSOrderedSame));
    return isDownloaded;
}

  • 其他說明

經測試注冊過的字體在應用關閉后下次開啟應用,判斷字體是否加載時返回為NO,為了保證正常使用需要每次啟動應用的時候先遍歷一遍字體文件夾將里面的字體文件都再次注冊一遍即可。參考代碼如下:

//注冊fonts目錄下面的所有字體文件
NSArray *ary = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:self.downloadPath error:nil];
for (NSString *p1 in ary)
{
    NSString *t1 = [self.downloadPath stringByAppendingPathComponent:p1];
    NSArray *ary1 = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:t1 error:nil];
    for (NSString *p1 in ary1)
    {
        NSString *t2 = [t1 stringByAppendingPathComponent:p1];
        if([t2 rangeOfString:@".ttf"].location != NSNotFound)
        {
            [self registerFont:t2];
        }
    }
}

以上就是對使用第三方字體的方法的介紹。

參考

曾靜的技術博客在iOS開發中使用自定義字體

 
 



作者:不簡單的風度
鏈接:https://www.jianshu.com/p/a02be724b7ec
來源:簡書
著作權歸作者所有。商業轉載請聯系作者獲得授權,非商業轉載請注明出處。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM