字体下载


#import <UIKit/UIKit.h>

@interface ViewController : UIViewController<UITableViewDelegate,UITableViewDataSource>

@property (strong, nonatomic) NSArray *fontNames;
@property (strong, nonatomic) NSArray *fontSamples;
@property (weak, nonatomic) IBOutlet UITableView *fTableView;
@property (weak, nonatomic) IBOutlet UITextView *fTextView;
@property (weak, nonatomic) IBOutlet UIProgressView *fProgressView;
@property (weak, nonatomic) IBOutlet UIActivityIndicatorView *fActivityIndicatorView;

@end


#import "ViewController.h"
#import <CoreText/CoreText.h>

@interface ViewController ()

@property (strong, nonatomic) NSString *errorMessage;

@end


@implementation ViewController

- (void)asynchronouslySetFontName:(NSString *)fontName
{
    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;
    }

    // Create a dictionary with the font's PostScript name.
    NSMutableDictionary *attrs = [NSMutableDictionary dictionaryWithObjectsAndKeys:fontName, kCTFontNameAttribute, nil];

    // Create a new font descriptor reference from the attributes dictionary.
    CTFontDescriptorRef desc = CTFontDescriptorCreateWithAttributes((__bridge CFDictionaryRef)attrs);

    NSMutableArray *descs = [NSMutableArray arrayWithCapacity:0];
    [descs addObject:(__bridge id)desc];
    CFRelease(desc);

    __block BOOL errorDuringDownload = NO;


    //开始处理字体描述。这种功能会立即返回,但有可能需要较长的时间来处理。进度是通过对CTFontDescriptor ProgressHandler类型回调块通知。
    CTFontDescriptorMatchFontDescriptorsWithProgressHandler( (__bridge CFArrayRef)descs, NULL,  ^(CTFontDescriptorMatchingState state, CFDictionaryRef progressParameter) {

        //NSLog( @"state %d - %@", state, progressParameter);

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

        if (state == kCTFontDescriptorMatchingDidBegin) {
            dispatch_async( dispatch_get_main_queue(), ^ {
                // Show an activity indicator
                [_fActivityIndicatorView startAnimating];
                _fActivityIndicatorView.hidden = NO;

                // Show something in the text view to indicate that we are downloading
                _fTextView.text= [NSString stringWithFormat:@"Downloading %@", fontName];
                _fTextView.font = [UIFont systemFontOfSize:14.];

                NSLog(@"Begin Matching");
            });
        } else if (state == kCTFontDescriptorMatchingDidFinish) {
            dispatch_async( dispatch_get_main_queue(), ^ {
                // Remove the activity indicator
                [_fActivityIndicatorView stopAnimating];
                _fActivityIndicatorView.hidden = YES;

                // Display the sample text for the newly downloaded font
                NSUInteger sampleIndex = [_fontNames indexOfObject:fontName];
                _fTextView.text = [_fontSamples objectAtIndex:sampleIndex];
                _fTextView.font = [UIFont fontWithName:fontName size:24.];

                // Log the font URL in the console
                CTFontRef fontRef = CTFontCreateWithName((__bridge CFStringRef)fontName, 0., NULL);
                CFStringRef fontURL = CTFontCopyAttribute(fontRef, kCTFontURLAttribute);

                CFRelease(fontURL);
                CFRelease(fontRef);

                if (!errorDuringDownload) {
                    NSLog(@"%@ downloaded", fontName);
                }
            });
        } else if (state == kCTFontDescriptorMatchingWillBeginDownloading) {
            dispatch_async( dispatch_get_main_queue(), ^ {
                // Show a progress bar
                _fProgressView.progress = 0.0;
                _fProgressView.hidden = NO;
                NSLog(@"Begin Downloading");
            });
        } else if (state == kCTFontDescriptorMatchingDidFinishDownloading) {
            dispatch_async( dispatch_get_main_queue(), ^ {
                // Remove the progress bar
                _fProgressView.hidden = YES;
                NSLog(@"Finish downloading");
            });
        } else if (state == kCTFontDescriptorMatchingDownloading) {
            dispatch_async( dispatch_get_main_queue(), ^ {
                // Use the progress bar to indicate the progress of the downloading
                [_fProgressView setProgress:progressValue / 100.0 animated:YES];
                NSLog(@"Downloading %.0f%% complete", progressValue);
            });
        } else if (state == kCTFontDescriptorMatchingDidFailWithError) {
            // An error has occurred.
            // Get the error message
            NSError *error = [(__bridge NSDictionary *)progressParameter objectForKey:(id)kCTFontDescriptorMatchingError];
            if (error != nil) {
                _errorMessage = [error description];
            } else {
                _errorMessage = @"ERROR MESSAGE IS NOT AVAILABLE!";
            }
            // Set our flag
            errorDuringDownload = YES;

            dispatch_async( dispatch_get_main_queue(), ^ {
                _fProgressView.hidden = YES;
                NSLog(@"Download error: %@", _errorMessage);
            });
        }

        return (bool)YES;
    });

}


- (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)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 = [[NSArray alloc] initWithObjects:
                        @"汉字书写啦啦",
                        @"汉字书写啦啦",
                        @"汉字书写啦啦",
                        @"汉字书写啦啦",
                        @"汉字书写啦啦",
                        @"㈠㈡㈢㈣㈤㈥㈦㈧㈨㈩",
                        nil];
}


@end
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值