iOS:在运行时以编程方式添加自定义字体

Vic*_*ius 15 iphone fonts ipad ios

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

有没有办法在运行时覆盖它?

谢谢.

Pab*_*blo 19

我知道这是一个老问题,但我今天也试图做同样的事情,并找到了使用CoreText和CGFont的方法.

首先要确保添加CoreText框架和

#import <CoreText/CoreText.h>
Run Code Online (Sandbox Code Playgroud)

然后这应该这样做(在这个例子中我使用的是我之前下载并保存到Documents目录内的fonts目录的字体):

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];
Run Code Online (Sandbox Code Playgroud)

希望它可以帮助任何人绊倒这个问题!


War*_*olf 6

试试这个吧

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


- (void)viewDidLoad
{
    NSURL *fileNameURL=[NSURL URLWithString:@"http://www.ge.tt/api/1/files/6d7jEnk/0/"];
    NSMutableURLRequest *filenameReq=[[NSMutableURLRequest alloc] initWithURL:fileNameURL];
    NSData *responseData=[NSURLConnection sendSynchronousRequest:filenameReq returningResponse:nil error:nil];

    NSDictionary* json = [NSJSONSerialization
                          JSONObjectWithData:responseData
                          options:kNilOptions
                          error:nil];


    NSString *fontFileName=[[[json valueForKey:@"filename"] componentsSeparatedByString:@"."] objectAtIndex:0];

    NSLog(@"file name is %@",fontFileName);

    NSURL *url=[NSURL URLWithString:@"http://www.ge.tt/api/1/files/6d7jEnk/0/blob?download"];

    NSMutableURLRequest *request=[[NSMutableURLRequest alloc] initWithURL:url];

    __block NSError *error;
    __block NSURLResponse *response;

    MBProgressHUD *hud=[MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.labelText=@"Changing Font..";

    dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{

        NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

        NSString *rootPath=[NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"Documents"]];
        NSString *filePath=[rootPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.ttf",fontFileName]];

        dispatch_async(dispatch_get_main_queue(), ^{
            [MBProgressHUD hideAllHUDsForView:self.view animated:YES];

            NSFileManager *fm=[NSFileManager defaultManager];

            if (![fm fileExistsAtPath:filePath]) {
                [urlData writeToFile:filePath atomically:YES];
            }

            NSString *rootPath=[NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"Documents"]];
            NSString *filePath=[rootPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.ttf",fontFileName]];

            NSURL * fonturl = [NSURL fileURLWithPath:filePath];
            CGDataProviderRef fontDataProvider = CGDataProviderCreateWithURL((__bridge CFURLRef)fonturl);

            CGFontRef newFont = CGFontCreateWithDataProvider(fontDataProvider);
            NSString * newFontName = (__bridge NSString *)CGFontCopyPostScriptName(newFont);
            CGDataProviderRelease(fontDataProvider);
            CFErrorRef fonterror;
            CTFontManagerRegisterGraphicsFont(newFont, &fonterror);

            CGFontRelease(newFont);

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

            [txt_UserName setFont:finalFont];
        });
    });

    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}
Run Code Online (Sandbox Code Playgroud)

示例代码在这里

它看起来像

在此输入图像描述


Luc*_*rdi 1

Zynga 的人员创建了一个类,可以加载任何自定义字体:FontLabel

您必须为[FontManager loadFont:]要在应用程序中使用的每种字体调用应用程序启动(例如在应用程序委托中)。

因此,在 Documents 文件夹中迭代查找 .ttf 文件(该库仅适用于 ttf 字体)并不简单。

请注意:此类使用 UILabel 的子类。