iOS:在运行时以编程方式添加自定义字体 [英] iOS: Programmatically add custom font during runtime

查看:211
本文介绍了iOS:在运行时以编程方式添加自定义字体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想允许我的应用程序用户在应用程序中使用自己的字体,通过在Documents目录(通过iTunes)中复制它们。但是,我找不到以这种方式使用自定义字体的方法,因为正确的方法取决于在应用程序的 Info.plist 中使用 UIAppFonts

有没有什么办法可以在运行时重写这个?



谢谢。

$ b $我知道这是一个古老的问题,但我今天正在尝试做同样的事情,并找到了一种使用CoreText和CGFont的方法。

$ b
$ b

首先确保您添加了CoreText框架和

  #import< CoreText / CoreText。 h取代; 

然后这样做(在这个例子中,我使用了一个我以前下载并保存的字体Documents目录中的字体目录):

  NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES); 
NSString * documentsDirectory = [paths objectAtIndex:0];
NSString * fontPath = [documentsDirectory stringByAppendingPathComponent:@Fonts / Chalkduster.ttf];
NSURL * url = [NSURL fileURLWithPath:fontPath];
CGDataProviderRef fontDataProvider = CGDataProviderCreateWithURL((__ bridge CFURLRef)url);
CGFontRef newFont = CGFontCreateWithDataProvider(fontDataProvider);
NSString * newFontName =(__bridge NSString *)CGFontCopyPostScriptName(newFont);
CGDataProviderRelease(fontDataProvider);
CFErrorRef错误;
CTFontManagerRegisterGraphicsFont(newFont,& error);
CGFontRelease(newFont);

UIFont * finalFont = [UIFont fontWithName:newFontName size:20.0f];

希望这可以帮助任何人解决这个问题!


I would like to allow my application users to use their own fonts in the app, by copying them inside the Documents directory (through iTunes). However, I can't find a way to use custom fonts in this way, since the right way to do it depends on using the UIAppFonts key in the app's Info.plist.

Is there any way to override this during runtime?

Thanks.

解决方案

I know this is an old question, but I was trying to do the same today and found a way using CoreText and CGFont.

First be sure you add the CoreText framework and

#import <CoreText/CoreText.h>

Then this should do it (in this example I am using a font I previously downloaded and saved to a fonts directory inside the Documents directory):

NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString * documentsDirectory = [paths objectAtIndex:0];
    NSString * fontPath = [documentsDirectory stringByAppendingPathComponent:@"Fonts/Chalkduster.ttf"];
    NSURL * url = [NSURL fileURLWithPath:fontPath];
    CGDataProviderRef fontDataProvider = CGDataProviderCreateWithURL((__bridge CFURLRef)url);
    CGFontRef newFont = CGFontCreateWithDataProvider(fontDataProvider);
    NSString * newFontName = (__bridge NSString *)CGFontCopyPostScriptName(newFont);
    CGDataProviderRelease(fontDataProvider);
    CFErrorRef error;
    CTFontManagerRegisterGraphicsFont(newFont, &error);
    CGFontRelease(newFont);

    UIFont * finalFont = [UIFont fontWithName:newFontName size:20.0f];

Hope it helps anyone stumbling across this question!

这篇关于iOS:在运行时以编程方式添加自定义字体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆