iOS中动态下载系统提供的多种中文字体

从iOS6开始,苹果开始支持动态下载官方提供的中文字体到系统中。使用动态下载中文字体的API可以动态的向iOS系统中添加字体,这些字体文件都是下载到系统的目录中,所以并不会造成应用体积的增加。不过,由于下载的时候需要使用的名字是PostScript名称,所以如果你真正要动态下载相应的字体的话,还需要使用Mac内自带的应用“字体册”来获得相应字体的PostScript名称。
相关API的介绍。
苹果提供了动态下载代码的Demo工程( https://developer.apple.com/library/ios/samplecode/DownloadFont/Listings/DownloadFont_ViewController_h.html)。
1、我们先判断字体是否已经被下载下来。
UIFont* aFont = [UIFont fontWithName:fontName size:12.];
// If the font is already downloaded

if (aFont && ([aFont.fontName compare:fontName] == NSOrderedSame || [aFont.familyName compare:fontName] == NSOrderedSame))
    {
        // Go ahead and display the sample text.
	NSUInteger sampleIndex = [_fontNames indexOfObject:fontName];

	_fTextView.text = [_fontSamples objectAtIndex:sampleIndex];
	_fTextView.font = [UIFont fontWithName:fontName size:24.];

	return;
    }
2、如果字体已经下载过了,则直接使用。否则我们需要先准备下载字体API需要的参数
// 用字体的PostScript名字创建一个Dictionary
NSMutableDictionary *attrs = [NSMutableDictionary dictionaryWithObjectsAndKeys:fontName, kCTFontNameAttribute, nil];

 // 创建一个字体描述对象CTFontDescriptorRef
CTFontDescriptorRef desc = CTFontDescriptorCreateWithAttributes((__bridge CFDictionaryRef)attrs);

  // 将字体描述对象放到一个NSMutableArray中
    NSMutableArray *descs = [NSMutableArray arrayWithCapacity:0];
    [descs addObject:(__bridge id)desc];
    CFRelease(desc);
3、准备好上面的descs变量后,就可以进行字体的下载了。
__blockBOOL errorDuringDownload = NO;

CTFontDescriptorMatchFontDescriptorsWithProgressHandler( (__bridge CFArrayRef)descs, NULL,  ^(CTFontDescriptorMatchingState state, CFDictionaryRef progressParameter) {

double progressValue = [[(__bridge NSDictionary *)progressParameter objectForKey:(id)kCTFontDescriptorMatchingPercentage] doubleValue];

if (state == kCTFontDescriptorMatchingDidBegin)
       	{
               NSLog(@"Begin Matching");
        }
        else if (state == kCTFontDescriptorMatchingDidFinish)
        {
               NSLog(@"%@ downloaded", fontName);
  	}
        else if (state == kCTFontDescriptorMatchingWillBeginDownloading)
        {
               NSLog(@"Begin Downloading");
        }
        else if (state == kCTFontDescriptorMatchingDidFinishDownloading)
        {
               NSLog(@"Finish downloading");
        }
        else if (state == kCTFontDescriptorMatchingDownloading)
        {
               NSLog(@"Downloading %.0f%% complete", progressValue);
        }
        else if (state == kCTFontDescriptorMatchingDidFailWithError)
        {
               NSLog(@"Download error: %@", _errorMessage);
        }
         return (bool)YES;
});
通常需要在下载字体完成后开始使用字体,一般是将相应的字体代码放到kCTFontDescriptorMatchingDidFinish那个条件中,可以像苹果官方网站示例代码一样,用GCD来修改UI的逻辑,也可以发Notification来通知相应的Controller.



你可能感兴趣的:(iOS中动态下载系统提供的多种中文字体)