码迷,mamicode.com
首页 > 其他好文 > 详细

UIFont-动态下载系统提供的字体-官方代码

时间:2015-07-31 20:29:56      阅读:218      评论:0      收藏:0      [点我收藏+]

标签:

一,工程目录

 

技术分享

 

二,AppDelegate.m

 

技术分享
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    
    
    ViewController *view=[[ViewController alloc]init];
    UINavigationController *nav=[[UINavigationController alloc]initWithRootViewController:view];
    self.window.backgroundColor=[UIColor whiteColor];
    self.window.rootViewController=nav;
    
    
    
    return YES;
}
技术分享

 

三,ViewController.h

 

技术分享
#import <UIKit/UIKit.h>

@interface ViewController : UIViewController
<UITableViewDelegate,UITableViewDataSource>
{
    UITableView *myTableView;
    NSArray *fontNames;
    NSArray *fontSamples;
}


@end
技术分享

 

四, ViewController.m

 

技术分享
#import "ViewController.h"
#import <CoreText/CoreText.h>

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    //初始化数据
    [self addData];
    //初始化界面
    [self addView];
    
}
#pragma -mark -functions
//初始化界面
-(void)addView
{
    myTableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 100, 320, 200)];
    myTableView.delegate=self;
    myTableView.dataSource=self;
    [self.view addSubview:myTableView];

}
//初始化数据
-(void)addData
{
    fontNames = [[NSArray alloc] initWithObjects:
                 @"STXingkai-SC-Light",
                 @"DFWaWaSC-W5",
                 @"FZLTXHK--GBK1-0",
                 @"STLibian-SC-Regular",
                 @"LiHeiPro",
                 @"HiraginoSansGB-W3",
                 nil];
    fontSamples = [[NSArray alloc] initWithObjects:
                   @"汉体书写信息技术标准相",
                   @"容档案下载使用界面简单",
                   @"支援服务升级资讯专业制",
                   @"作创意空间快速无线上网",
                   @"兙兛兞兝兡兣嗧瓩糎",
                   @"㈠㈡㈢㈣㈤㈥㈦㈧㈨㈩",
                   nil];

}
#pragma -mark -UITableViewDelegate
- (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]];
}
#pragma -mark -functions
//字体开始进行下载
- (void)asynchronouslySetFontName:(NSString *)fontName
{
    UIFont* aFont = [UIFont fontWithName:fontName size:12.];
    //判断字体是否已经被下载
    if (aFont && ([aFont.fontName compare:fontName] == NSOrderedSame || [aFont.familyName compare:fontName] == NSOrderedSame)) {
        NSLog(@"字体已经被下载");
        return;
    }
    
    //用字体的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);
    
    __block BOOL errorDuringDownload = NO;
    
    //开始对字体进行下载
    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(), ^ {
                NSLog(@"字体已经匹配");
                });
        } else if (state == kCTFontDescriptorMatchingDidFinish) {
            dispatch_async( dispatch_get_main_queue(), ^ {
                NSLog(@"字体下载完成");
                      // 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(), ^ {
                NSLog(@"字体开始下载");
            });
        } else if (state == kCTFontDescriptorMatchingDidFinishDownloading) {
            dispatch_async( dispatch_get_main_queue(), ^ {
                NSLog(@"字体下载完成");
                });
        } else if (state == kCTFontDescriptorMatchingDownloading) {
            dispatch_async( dispatch_get_main_queue(), ^ {
                NSLog(@"下载进度");
            });
        } else if (state == kCTFontDescriptorMatchingDidFailWithError) {
            NSLog(@"下载失败");
            
            NSError *error = [(__bridge NSDictionary *)progressParameter objectForKey:(id)kCTFontDescriptorMatchingError];
            if (error != nil) {
                NSLog(@"errorMessage--%@-",[error description]);
            } else {
                NSLog(@"error message is not available");
            }
            errorDuringDownload = YES;
            dispatch_async( dispatch_get_main_queue(), ^ {
                NSLog(@"Download error: %@", [error description]);
            });
        }
        
        return (bool)YES;
    });
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
技术分享

 

参考资料:《iOS开发进阶》 -唐巧


版权声明:本文为博主原创文章,未经博主允许不得转载。

UIFont-动态下载系统提供的字体-官方代码

标签:

原文地址:http://blog.csdn.net/fanqingtulv/article/details/47173677

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!