使用CoreText动态下载更换字体

#import "ViewController.h"

#import <CoreText/CoreText.h>

 

@interface ViewController ()<UITableViewDataSource,UITableViewDelegate>

@property (weak, nonatomic) IBOutlet UITableView *fTableView;

@property (weak, nonatomic) IBOutlet UITextView *fTextView;

@property (weak, nonatomic) IBOutlet UIActivityIndicatorView *fActivityIndicatorView;

@property (weak, nonatomic) IBOutlet UIProgressView *fProgressView;

 

@property (strong, nonatomic) NSArray *fontNames;//字体的名字

@property (copy, nonatomic) NSString *fontSamples;//展示的话

@property (copy, nonatomic) NSString *errorMessage;

 

@end

 

@implementation ViewController

 

详细代码如下:

 

  1 - (void)viewDidLoad
  2 {
  3     [super viewDidLoad];
  4     
  5     self.fontNames = [[NSArray alloc] initWithObjects:
  6                       @"STXingkai-SC-Light",
  7                       @"DFWaWaSC-W5",
  8                       @"FZLTXHK--GBK1-0",
  9                       @"STLibian-SC-Regular",
 10                       @"LiHeiPro",
 11                       @"HiraginoSansGB-W3",
 12                       nil];
 13     self.fontSamples = @"让优秀的人拥有值得的归宿。";
 14 }
 15 
 16 - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
 17     return [_fontNames count];
 18 }
 19 
 20 
 21 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
 22     static NSString *MyIdentifier = @"MyIdentifier";
 23     UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
 24     if (cell == nil) {
 25         cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:MyIdentifier];
 26     }
 27     cell.textLabel.text = _fontNames[indexPath.row];
 28     return cell;
 29 }
 30 
 31 
 32 - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
 33     [self asynchronouslySetFontName:_fontNames[indexPath.row]];
 34     if ([self.fTextView isFirstResponder])
 35         [self.fTextView resignFirstResponder];
 36 }
 37 
 38 - (void)asynchronouslySetFontName:(NSString *)fontName{
 39     if ([self isFontDownloaded:fontName]) {
 40         _fTextView.text = _fontSamples;
 41         _fTextView.font = [UIFont fontWithName:fontName size:24.];
 42         return;
 43     }else{
 44         //如果名为fontName的字体尚未下载,则动态下载。使用UIActivityIndicatorView和UIProgressView辅助完成下载过程
 45         NSMutableDictionary *attrs = [NSMutableDictionary dictionaryWithObjectsAndKeys:fontName, kCTFontNameAttribute, nil];
 46         CTFontDescriptorRef desc = CTFontDescriptorCreateWithAttributes((__bridge CFDictionaryRef)attrs);
 47         NSMutableArray *descs = [NSMutableArray arrayWithCapacity:0];
 48         [descs addObject:(__bridge id)desc];
 49         CFRelease(desc);
 50 
 51         __block BOOL errorDuringDownload = NO;
 52         CTFontDescriptorMatchFontDescriptorsWithProgressHandler( (__bridge CFArrayRef)descs, NULL,  ^(CTFontDescriptorMatchingState state, CFDictionaryRef progressParameter) {
 53             
 54             double progressValue = [[(__bridge NSDictionary *)progressParameter objectForKey:(id)kCTFontDescriptorMatchingPercentage] doubleValue];
 55             
 56             if (state == kCTFontDescriptorMatchingDidBegin) {
 57                 dispatch_async( dispatch_get_main_queue(), ^ {
 58                     [_fActivityIndicatorView startAnimating];
 59                     _fActivityIndicatorView.hidden = NO;
 60                     _fTextView.text= [NSString stringWithFormat:@"正在下载 %@ 字体", fontName];
 61                     _fTextView.font = [UIFont systemFontOfSize:14.];
 62                 });
 63             } else if (state == kCTFontDescriptorMatchingDidFinish) {
 64                 dispatch_async( dispatch_get_main_queue(), ^ {
 65                     [_fActivityIndicatorView stopAnimating];
 66                     _fActivityIndicatorView.hidden = YES;
 67                     _fTextView.text = _fontSamples;
 68                     _fTextView.font = [UIFont fontWithName:fontName size:24.];
 69                     if (!errorDuringDownload) {
 70                         NSLog(@"字体 %@ 下载完成", fontName);
 71                     }
 72                 });
 73             } else if (state == kCTFontDescriptorMatchingWillBeginDownloading) {
 74                 dispatch_async( dispatch_get_main_queue(), ^ {
 75                     _fProgressView.progress = 0.0;
 76                     _fProgressView.hidden = NO;
 77                 });
 78             } else if (state == kCTFontDescriptorMatchingDidFinishDownloading) {
 79                 dispatch_async( dispatch_get_main_queue(), ^ {
 80                     _fProgressView.hidden = YES;
 81                 });
 82             } else if (state == kCTFontDescriptorMatchingDownloading) {
 83                 dispatch_async( dispatch_get_main_queue(), ^ {
 84                     [_fProgressView setProgress:progressValue / 100.0 animated:YES];
 85                 });
 86             } else if (state == kCTFontDescriptorMatchingDidFailWithError) {
 87                 NSError *error = [(__bridge NSDictionary *)progressParameter objectForKey:(id)kCTFontDescriptorMatchingError];
 88                 if (error != nil) {
 89                     _errorMessage = [error description];
 90                 } else {
 91                     _errorMessage = @"ERROR MESSAGE IS NOT AVAILABLE!";
 92                 }
 93                 errorDuringDownload = YES;
 94                 dispatch_async( dispatch_get_main_queue(), ^ {
 95                     _fProgressView.hidden = YES;
 96                     NSLog(@"下载错误: %@", _errorMessage);
 97                 });
 98             }
 99             
100             return (bool)YES;
101         });
102     }
103 }
104 
105 
106 - (BOOL)isFontDownloaded:(NSString *)fontName{
107     UIFont * aFont = [UIFont fontWithName:fontName size:12.0];
108     return (aFont && ([aFont.fontName compare:fontName] == NSOrderedSame || [aFont.familyName compare:fontName] == NSOrderedSame));
109 }

 

实现效果:

 

原文地址:https://www.cnblogs.com/kfgcs/p/6378575.html