我想有一个应用程序包括一个自定义字体渲染文本,加载它,然后使用它与标准UIKit元素如UILabel。这可能吗?


当前回答

在你现有的iOS应用程序上添加一个新的字体是非常容易的。

你只需要添加字体,如font.ttf到你的资源文件夹。

打开应用程序info.plist。添加一个新行作为“Fonts provided by application”,并输入字体名称为font.ttf。

设置字体时执行setFont:"相应字体名称"

你可以通过NSArray *check = [UIFont familyNames];来检查你的字体是否被添加。

它返回应用程序支持的所有字体。

其他回答

在iOS 4中有一种使用自定义字体的简单方法。

将您的字体文件(例如,chalkdust .ttf)添加到XCode项目的资源文件夹中。 开放的信息。plist并添加一个名为UIAppFonts的新键。这个键的类型应该是array。 将您的自定义字体名称添加到该数组,包括扩展名(chalkdust .ttf)。 现在你可以在你的应用程序中使用[UIFont fontWithName:@"Chalkduster" size:16]。

不幸的是,IB不允许使用自定义字体初始化标签。看这个问题来解决这个问题。我最喜欢的解决方案是使用自定义UILabel子类:

@implementation CustomFontLabel

- (id)initWithCoder:(NSCoder *)decoder
{
    if (self = [super initWithCoder: decoder])
    {
        [self setFont: [UIFont fontWithName: @"Chalkduster" size: self.font.pointSize]];
    }
    return self;
}

@end

这是如何做这件事的一步一步的说明。不需要额外的库或任何特殊的编码。

http://shang-liang.com/blog/custom-fonts-in-ios4/

大多数时候问题在于字体而不是方法。最好的方法是使用一种肯定有效的字体,比如verdana或geogia。然后更改为想要的字体。如果它不起作用,可能是字体名称不正确,或者字体格式不正确。

编辑:这个答案在iOS3.2失效;使用UIAppFonts

我能够成功加载自定义UIFonts的唯一方法是通过私有的GraphicsServices框架。

下面将加载应用程序主包中的所有.ttf字体:

BOOL GSFontAddFromFile(const char * path);
NSUInteger loadFonts()
{
    NSUInteger newFontCount = 0;
    for (NSString *fontFile in [[NSBundle mainBundle] pathsForResourcesOfType:@"ttf" inDirectory:nil])
        newFontCount += GSFontAddFromFile([fontFile UTF8String]);
    return newFontCount;
}

一旦字体被加载,它们就可以像apple提供的字体一样使用:

NSLog(@"Available Font Families: %@", [UIFont familyNames]);
[label setFont:[UIFont fontWithName:@"Consolas" size:20.0f]];

GraphicsServices甚至可以在运行时加载,以防API在未来消失:

#import <dlfcn.h>
NSUInteger loadFonts()
{
    NSUInteger newFontCount = 0;
    NSBundle *frameworkBundle = [NSBundle bundleWithIdentifier:@"com.apple.GraphicsServices"];
    const char *frameworkPath = [[frameworkBundle executablePath] UTF8String];
    if (frameworkPath) {
        void *graphicsServices = dlopen(frameworkPath, RTLD_NOLOAD | RTLD_LAZY);
        if (graphicsServices) {
            BOOL (*GSFontAddFromFile)(const char *) = dlsym(graphicsServices, "GSFontAddFromFile");
            if (GSFontAddFromFile)
                for (NSString *fontFile in [[NSBundle mainBundle] pathsForResourcesOfType:@"ttf" inDirectory:nil])
                    newFontCount += GSFontAddFromFile([fontFile UTF8String]);
        }
    }
    return newFontCount;
}

我建议大家参考我最喜欢的一个简短教程:http://codewithchris.com/common-mistakes-with-adding-custom-fonts-to-your-ios-app/,上面的信息都来自这个网站。

第1步-将.ttf或.otf从Finder拖到项目中

注意-请确保在主应用程序目标上单击“添加到目标”框

如果你忘记单击将其添加到目标,然后单击项目层次结构中的字体文件,在右侧面板中单击目标会员部分中的主应用程序目标

要确保字体是应用目标的一部分,请确保它们出现在构建阶段的Copy Bundle Resources中

步骤2 -添加字体文件名到你的Plist

去自定义iOS目标属性在你的信息部分,并添加一个关键字,在该部分的项目,称为字体提供的应用程序(你应该看到它作为一个选项,当你输入它,它将自己设置为一个数组。点击小箭头打开数组项,输入你添加的.ttf或.otf文件的名称,让你的应用程序知道这些是你想要可用的字体文件

注意-如果你的应用程序在这一步之后崩溃,那么检查你在这里添加的项目的拼写

步骤3 -找出字体的名称,这样你就可以调用它们

通常情况下,应用程序看到的字体名称与基于该字体的文件名所认为的不同,将其放入代码中,并查看应用程序所做的日志,以查看在代码中调用的字体名称

斯威夫特

for family: String in UIFont.familyNames(){
  print("\(family)")
  for names: String in UIFont.fontNamesForFamilyName(family){
      print("== \(names)")
  }
}

Objective - C

for (NSString* family in [UIFont familyNames]){
    NSLog(@"%@", family);
    for (NSString* name in [UIFont fontNamesForFamilyName: family]){
        NSLog(@"  %@", name);
    }
}

你的日志应该是这样的:

步骤4 -使用步骤3中的名称使用新的自定义字体

斯威夫特

 label.font = UIFont(name: "SourceSansPro-Regular", size: 18)

Objective - C

 label.font = [UIFont fontWithName:@"SourceSansPro-Regular" size:18];

Swift,代码方式:(也适用于Swift 2.0)

添加所需的字体到你的项目(就像添加图像,只需拖动到Xcode),确保他们是针对你的项目 添加这个方法并加载自定义字体(推荐在appDelegate didFinishLaunchingWithOptions中)

func loadFont(filePath: String) {

    let fontData = NSData(contentsOfFile: filePath)!

    let dataProvider = CGDataProviderCreateWithCFData(fontData)
    let cgFont = CGFontCreateWithDataProvider(dataProvider)!

    var error: Unmanaged<CFError>?
    if !CTFontManagerRegisterGraphicsFont(cgFont, &error) {
        let errorDescription: CFStringRef = CFErrorCopyDescription(error!.takeUnretainedValue())
        print("Unable to load font: %@", errorDescription, terminator: "")
    }

}

使用的例子:

if let fontPath = NSBundle.mainBundle().pathForResource("My-Font", ofType: "ttf"){
      loadFont(fontPath)
}

使用字体:

UIFont(name: "My-Font", size: 16.5)