iOS 使用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

详细代码如下:

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.fontNames = [[NSArray alloc] initWithObjects:
                      @"STXingkai-SC-Light",
                      @"DFWaWaSC-W5",
                      @"FZLTXHK--GBK1-0",
                      @"STLibian-SC-Regular",
                      @"LiHeiPro",
                      @"HiraginoSansGB-W3",
                      nil];
    self.fontSamples = @"让优秀的人拥有值得的归宿。";
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [_fontNames count];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *MyIdentifier = @"MyIdentifier";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:MyIdentifier];
    }
    cell.textLabel.text = _fontNames[indexPath.row];
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [self asynchronouslySetFontName:_fontNames[indexPath.row]];
    if ([self.fTextView isFirstResponder])
        [self.fTextView resignFirstResponder];
}

- (void)asynchronouslySetFontName:(NSString *)fontName{
    if ([self isFontDownloaded:fontName]) {
        _fTextView.text = _fontSamples;
        _fTextView.font = [UIFont fontWithName:fontName size:24.];
        return;
    }else{
        //如果名为fontName的字体尚未下载,则动态下载。使用UIActivityIndicatorView和UIProgressView辅助完成下载过程
        NSMutableDictionary *attrs = [NSMutableDictionary dictionaryWithObjectsAndKeys:fontName, kCTFontNameAttribute, nil];
        CTFontDescriptorRef desc = CTFontDescriptorCreateWithAttributes((__bridge CFDictionaryRef)attrs);
        NSMutableArray *descs = [NSMutableArray arrayWithCapacity:0];
        [descs addObject:(__bridge id)desc];
        CFRelease(desc);

        __block BOOL errorDuringDownload = NO;
        CTFontDescriptorMatchFontDescriptorsWithProgressHandler( (__bridge CFArrayRef)descs, NULL,  ^(CTFontDescriptorMatchingState state, CFDictionaryRef progressParameter) {
            
            double progressValue = [[(__bridge NSDictionary *)progressParameter objectForKey:(id)kCTFontDescriptorMatchingPercentage] doubleValue];
            
            if (state == kCTFontDescriptorMatchingDidBegin) {
                dispatch_async( dispatch_get_main_queue(), ^ {
                    [_fActivityIndicatorView startAnimating];
                    _fActivityIndicatorView.hidden = NO;
                    _fTextView.text= [NSString stringWithFormat:@"正在下载 %@ 字体", fontName];
                    _fTextView.font = [UIFont systemFontOfSize:14.];
                });
            } else if (state == kCTFontDescriptorMatchingDidFinish) {
                dispatch_async( dispatch_get_main_queue(), ^ {
                    [_fActivityIndicatorView stopAnimating];
                    _fActivityIndicatorView.hidden = YES;
                    _fTextView.text = _fontSamples;
                    _fTextView.font = [UIFont fontWithName:fontName size:24.];
                    if (!errorDuringDownload) {
                        NSLog(@"字体 %@ 下载完成", fontName);
                    }
                });
            } else if (state == kCTFontDescriptorMatchingWillBeginDownloading) {
                dispatch_async( dispatch_get_main_queue(), ^ {
                    _fProgressView.progress = 0.0;
                    _fProgressView.hidden = NO;
                });
            } else if (state == kCTFontDescriptorMatchingDidFinishDownloading) {
                dispatch_async( dispatch_get_main_queue(), ^ {
                    _fProgressView.hidden = YES;
                });
            } else if (state == kCTFontDescriptorMatchingDownloading) {
                dispatch_async( dispatch_get_main_queue(), ^ {
                    [_fProgressView setProgress:progressValue / 100.0 animated:YES];
                });
            } else if (state == kCTFontDescriptorMatchingDidFailWithError) {
                NSError *error = [(__bridge NSDictionary *)progressParameter objectForKey:(id)kCTFontDescriptorMatchingError];
                if (error != nil) {
                    _errorMessage = [error description];
                } else {
                    _errorMessage = @"ERROR MESSAGE IS NOT AVAILABLE!";
                }
                errorDuringDownload = YES;
                dispatch_async( dispatch_get_main_queue(), ^ {
                    _fProgressView.hidden = YES;
                    NSLog(@"下载错误: %@", _errorMessage);
                });
            }
            
            return (bool)YES;
        });
    }
}


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

实现效果:

特别声明:文章多为网络转载,资源使用一般不提供任何帮助,特殊资源除外,如有侵权请联系!
技术狗 » iOS 使用CoreText动态下载更换字体