【问题标题】:Xcode Objective-C: Download a custom font and display it in a UILabelXcode Objective-C:下载自定义字体并将其显示在 UILabel 中
【发布时间】:2020-02-03 12:17:00
【问题描述】:

首先:是否可以下载自定义字体并将其显示在 UILabel 中?

我正在使用此代码从 Internet 下载自定义字体并将其显示在 UILabel 中,但它不起作用。

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

@synthesize txt_UserName;

- (void)viewDidLoad {
    [super viewDidLoad];

    // 1
    NSString *dataUrl = @"https://dl.dafont.com/dl/?f=stars_fighters";
    NSURL *url = [NSURL URLWithString:dataUrl];

    // 2
    NSURLSessionDataTask *downloadTask = [[NSURLSession sharedSession] dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        // 4: Handle response here
        if (error == nil) {
            NSLog(@"no error!");
            if (data != nil) {
                NSLog(@"There is data!");
                [self loadFont:data];
            }
        } else {
            NSLog(@"%@", error.localizedDescription);
        }
    }];

    // 3
    [downloadTask resume];


}

- (void)loadFont:(NSData *)data
{
    NSData *inData = data;
    CFErrorRef error;
    CGDataProviderRef provider = CGDataProviderCreateWithCFData((CFDataRef)data);
    CGFontRef font = CGFontCreateWithDataProvider(provider);
    if(!CTFontManagerRegisterGraphicsFont(font, &error)){
        CFStringRef errorDescription = CFErrorCopyDescription(error);
        NSLog(@"Failed to load font: %@", errorDescription);
      //  CFRelease(errorDescription);
    }
//    CFRelease(font);
 //   CFRelease(provider);

    CTFontRef ctFont = CTFontCreateWithGraphicsFont(font, 30, NULL, NULL);
    UIFont *uiFont = CFBridgingRelease(ctFont);

    dispatch_async(dispatch_get_main_queue(), ^{
        [self.txt_UserName setFont:uiFont];
    });

    [self fontTest];
}

- (void)fontTest
{
    NSArray *fontFamilies = [UIFont familyNames];
    for (int i = 0; i < [fontFamilies count]; i++) {
        NSString *fontFamily = [fontFamilies objectAtIndex:i];
        NSArray *fontNames = [UIFont fontNamesForFamilyName:[fontFamilies objectAtIndex:i]];
        NSLog (@"%@: %@", fontFamily, fontNames);
    }
}

@end  

无论如何我都会收到此错误:加载字体失败:操作无法完成。无效参数

在自定义字体的位置,我得到了一个默认的 iOS 字体。

【问题讨论】:

  • 您的 URL 下载了一个 .zip 文件,其中包含 2 个 .ttf 文件。您需要解压缩并将文件存储在本地。

标签: objective-c xcode fonts


【解决方案1】:

当然可以下载自定义字体并将其显示在 UILabel 中,这是我运行良好的代码:

第一步:假设字体文件已经保存在沙箱路径Documents / StarsFighters.ttf,加载字体并获取字体名称(在YOUR_CLASS .m文件中):

+ (NSString *)loadFontAndReturnFontName {
    NSString *imgFilePath = [NSString stringWithFormat:@"%@/Documents/StarsFighters.ttf",NSHomeDirectory()];
    NSURL *fontUrl = [NSURL fileURLWithPath:imgFilePath];
    CGDataProviderRef fontDataProvider =  CGDataProviderCreateWithURL((__bridge CFURLRef)fontUrl);
    CGFontRef fontRef = CGFontCreateWithDataProvider(fontDataProvider);
    CGDataProviderRelease(fontDataProvider);
    CTFontManagerRegisterGraphicsFont(fontRef, NULL);
    NSString *fontName = CFBridgingRelease(CGFontCopyPostScriptName(fontRef));
    return fontName;
}

第二步:使用自定义字体

NSString *fontname = [YOUR_CLASS loadFontAndReturnFontName];
//fontname is @"StarsFighters",best set it to a global variable or save it
YOUR_LABEL.font = [UIFont fontWithName:fontname size:18.0];

【讨论】:

  • 谢谢!对于下载字体,您使用与我相同的代码?
  • 另外,我在控制台上得到了这个:CoreText 注意:客户端请求的名称“.Helvetica NeueUI”,它将获得 TimesNewRomanPSMT 而不是预期的字体。所有系统 UI 字体访问都应通过适当的 API,例如 CTFontCreateUIFontForLanguage() 或 +[UIFont systemFontOfSize:]。 2020-02-03 09:23:09.522915+0100 测试字体[285:6177] CoreText 注意:在 CTFontLogSystemFontNameRequest 上设置断点进行调试。
  • 你的下载链接是一个zip文件,你需要解压里面的ttf文件。为了方便,我直接用这个链接测试了:https://raw.githubusercontent.com/wooodypan/AlgorithmWithMac/master/AlgorithmWithMac/Stars%20Fighters.ttf
  • 你可以使用ZipArchive解压你的zip文件:github.com/ZipArchive/ZipArchive
猜你喜欢
  • 1970-01-01
  • 2011-06-05
  • 2015-12-21
  • 2011-07-21
  • 2014-09-11
  • 2011-02-12
  • 2011-07-21
  • 2015-12-11
  • 2011-11-18
相关资源
最近更新 更多