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


当前回答

目前还没有发布,但下一个版本的cocos2d (2d游戏框架)将支持可变长度的位图字体作为角色地图。

http://code.google.com/p/cocos2d-iphone/issues/detail?id=317

作者没有确定这个版本的发布日期,但我确实看到一个帖子说它将在未来一两个月发布。

其他回答

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

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

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

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

编辑:这个答案在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 3.1.2上尝试了这个页面上的各种建议,以下是我的结论:

简单地使用[UIFont fontWithName:size:]与资源目录中的字体将不起作用,即使使用FontForge设置了FOND名称。

[UIFont fontWithName:size:]将工作,如果字体首先使用GSFontAddFromFile加载。但是GSFontAddFromFile不是iOS 3.1.2的一部分,所以它必须像@rpetrich所描述的那样动态加载。

如果你使用的是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.

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