【发布时间】: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