iOS开发中涉及的字体问题

iOS中常见3种方法来控制字体,下面根据我在网上学习总结的内容发布(已完美避过所有坑,iOS8.4)

一.系统默认的设置字体方法(只对英文和数字生效的方法)

1.系统默认提供的字体主要是指UIFont中提供的字体,其使用代码为:

_label.font = [UIFont fontWithName:@"Marion" size:20.0f];

2.或者是通过字体详细字典对字体属性进行设置

/*

     UIFontDescriptorFamilyAttribute:设置字体家族名

     UIFontDescriptorNameAttribute  :设置字体的字体名

     UIFontDescriptorSizeAttribute  :设置字体尺寸

     UIFontDescriptorMatrixAttribute:设置字体形变   

*/

//创建描述字典

NSDictionary *fontDict = @{UIFontDescriptorFamilyAttribute:@"Marion",UIFontDescriptorNameAttribute:@"Marion-Regular",UIFontDescriptorSizeAttribute:@20.0f,UIFontDescriptorMatrixAttribute:[NSValue valueWithCGAffineTransform:CGAffineTransformMakeRotation(M_1_PI*1.5)]};

//创建字体描述对象

UIFontDescriptor *attributeFontDescriptor = [UIFontDescriptor fontDescriptorWithFontAttributes:fontDict];

//设置字体

 _label.font = [UIFont fontWithDescriptor:attributeFontDescriptor size:0.0];

其中的字体家族名和字体名可以通过以下方法获取

NSLog(@"%@",[UIFont familyNames]);

以上两种方法均可以为label设置字体,但是全部是只针对英文数字,对中文无效。要想改变中文字体还需要使用后面两种办法

 

二.将字体包直接打入工程,内嵌字体(对中英数字有效)

现在网上不管是windows字体,还是Android字体只要是ttf格式的,或者是苹果提供的ttc、otf格式,一般iOS程序都支持内嵌

1.认识字体册

MAC -> Launchpad -> 其他 -> 字体册

 

 

 

2.打开字体册后可以看到有各种中英文字体,可点击各种按钮试看功能,当前我们需要设置中文,如下图所示,注意红线部分

 

3.特别要注意这个PostScript名称,这个名称是我们在动态下载字体以及程序里设置Label字体时所要填写的字体真实名称,而非一会要提取的字体文件名称

4.右键字体,选择当前字体文件,如果字体尚未下载则先添加字体。拖入Xcode工程中,注意勾选复制以及tagert

 

 

 

5.如果上面一步没有勾选复制或者targets,则会出现即使添加了字体并设置也没有任何效果的状况,这时候需要去Xcode设置中 -> Build Phases -> Copy Bundle Resources中手动添加当前的字体文件

 

6.在Xcode工程中的Info.plist文件中添加键Fonts provided by application,设置字体文件名为值(是字体文件名,要带上扩展名,不一定跟PostScript同名)

 

7.设置Label字体名为当前导入字体的PostScrip名称,即可使用

_label.font = [UIFont fontWithName:@"YuppySC-Regular" size:20.0f];

 

三.动态修改当前应用内字体(iOS6之后出现API,对中英数字有效)

这部分引用唐巧先生关于字体设置的博文,另外注意的是这个方法目前不完美,每次重启APP时会重新自动下载字体并加载,初步判断是因为字体下载到系统目录而非内嵌应用沙盒导致的

唐巧博客:

http://blog.devtang.com/2013/08/11/ios-asian-font-download-introduction/

苹果官方文档:

https://developer.apple.com/library/ios/samplecode/DownloadFont/Listings/DownloadFont_ViewController_m.html#//apple_ref/doc/uid/DTS40013404-DownloadFont_ViewController_m-DontLinkElementID_6

 

1.首先依然需要去字体册里寻找PostScript名称,这次不管是下载还是设置都要使用这个名字

2.代码示例

- (void)viewDidLoad {

    [super viewDidLoad];

    _label = [[UILabel alloc] initWithFrame:CGRectMake(50, 200, 300, 20)];

    _label.text = @"我懂得";

    [self.view addSubview:_label];

    BOOL is = [self isFontDownloaded:@"HanziPenSC-W3"];

    if (is)

    {

        _label.font = [UIFont fontWithName:@"HanziPenSC-W3" size:15.0f];

    }

    else

    {

        [self downloadFontWithAppleServers:@"HanziPenSC-W3"];

    }

}

 

- (BOOL)isFontDownloaded:(NSString *)fontName

{

    UIFont *aFont = [UIFont fontWithName:fontName size:15.0f];

    if (aFont && ([aFont.fontName compare:fontName] == NSOrderedSame || [aFont.familyName compare:fontName] == NSOrderedSame))

    {

        return YES;

    }

    else

    {

        return NO;

    }

}

  

- (void)downloadFontWithAppleServers:(NSString *)fontName

{

    //用字体的PostScript名字创建一个字典

    //注意:这个方法必须导入#import <CoreText/CoreText.h>

    NSMutableDictionary *attrs = [NSMutableDictionary dictionaryWithObjectsAndKeys:fontName,kCTFontNameAttribute, nil];

    

    //创建一个字体描述对象CTFontDescriptorRef

    CTFontDescriptorRef desc = CTFontDescriptorCreateWithAttributes((__bridge CFDictionaryRef)attrs);

    

    //将字体描述对象放到一个可变数组中

    NSMutableArray *descArray = [NSMutableArray array];

    [descArray addObject:(__bridge id)desc];

    

    //定义一个下载错误变量

    __block BOOL errorDuringDownload = NO;

    

    //开始进行字体下载

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

        

        //获取一个下载进度值

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

        

        if (state == kCTFontDescriptorMatchingDidBegin)

        {

            NSLog(@"字体已经匹配成功");

        }

        else if (state == kCTFontDescriptorMatchingDidFinish)

        {

            if (!errorDuringDownload)

            {

                NSLog(@"字体%@已经下载完成",fontName);

            }

            //返回主线程刷新

            dispatch_async(dispatch_get_main_queue(), ^{

                _label.font = [UIFont fontWithName:fontName size:15.0f];

            });

        }

        else if (state == kCTFontDescriptorMatchingWillBeginDownloading)

        {

            NSLog(@"字体开始下载");

        }

        else if (state == kCTFontDescriptorMatchingDownloading)

        {

            NSLog(@"下载进度%.0f%%",progressValue);

        }

        else if (state == kCTFontDescriptorMatchingDidFinishDownloading)

        {

            NSLog(@"字体下载完成");

        }

        else if (state == kCTFontDescriptorMatchingDidFailWithError)

        {

            NSError *error = [(__bridge NSDictionary *)progressParameter objectForKey:(id)kCTFontDescriptorMatchingError];

            NSString *errorMessage = @"";

            

            if (error != nil)

            {

                errorMessage = [error description];

            }

            else

            {

                errorMessage = @"没有可用的错误信息";

            }

            

            //设置标志

            errorDuringDownload = YES;

            NSLog(@"下载字体时发生错误:%@",errorMessage);

        }

        

        return (BOOL)YES;

    });

    

}

 

posted @ 2016-03-23 13:25  抓狂的ZXY  阅读(2705)  评论(0编辑  收藏  举报