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


当前回答

一个重要的注意事项:您应该使用与字体相关的“PostScript名称”,而不是其全名或家族名称。此名称通常与字体的正常名称不同。

其他回答

查找ATSApplicationFontsPath

一个简单的plist条目,允许你在你的应用程序资源文件夹中包括字体文件,他们“只是工作”在你的应用程序中。

正如之前所有的答案所表明的,这是非常有可能的,而且在更新的iOS版本中非常容易。

我知道这不是一个技术上的答案,但因为很多人都做错了(这实际上违反了许可,如果你被起诉,可能会花费你很多钱),让我在这里强调一个警告:在iOS(或任何其他类型)应用程序中嵌入自定义字体基本上是重新分配字体。大多数商业字体的许可都禁止再分发,所以请确保您按照许可行事。

编辑:这个答案在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;
}

在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

首先将.odt格式的字体添加到资源中,在本例中我们将使用DINEngschriftStd。Otf,然后使用这段代码将字体分配给标签

[theUILabel setFont:[UIFont fontWithName:@"DINEngschriftStd" size:21]];

要确保你的字体被加载到项目中,只需调用

NSLog(@"Available Font Families: %@", [UIFont familyNames]);

在.plist中,必须声明字体。只需添加一个'由应用程序提供的字体'记录,并添加一个带有字体名称的item 0字符串(DINEngschriftStd.otf)