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


当前回答

更好的解决方案是在你的信息中添加一个新的属性“应用程序提供的字体”。plist文件。

然后,你可以使用你的自定义字体像正常的UIFont。

其他回答

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

也许作者忘记给字体起一个Mac喜欢的名字了?

在FontForge中打开字体,然后进入元素>字体信息 有一个“Mac”选项,你可以设置喜爱的名称。 在文件>导出字体下,您可以创建一个新的ttf

你也可以试试导出对话框中的“Apple”选项。

免责声明:我不是IPhone开发者!

如果你使用的是xcode 4.3,你必须将字体添加到拷贝Bundle资源下的构建阶段,根据线程https://stackoverflow.com/users/1292829/arne,自定义字体xcode 4.3。这对我来说很有效,下面是我在应用程序中使用自定义字体的步骤:

Add the font to your project. I dragged and dropped the OTF (or TTF) files to a new group I created and accepted xcode's choice of copying the files over to the project folder. Create the UIAppFonts array with your fonts listed as items within the array. Just the names, not the extension (e.g. "GothamBold", "GothamBold-Italic"). Click on the project name way at the top of the Project Navigator on the left side of the screen. Click on the Build Phases tab that appears in the main area of xcode. Expand the "Copy Bundle Resources" section and click on "+" to add the font. Select the font file from the file navigator that pops open when you click on the "+". Do this for every font you have to add to the project.

在查找器和“获取信息”中找到TTF。在“全名:”的标题下,它给了我一个名字,然后我用fontWithName(我只是复制和粘贴了确切的名字,在这种情况下,没有'.ttf'扩展是必要的)。

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

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