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


当前回答

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

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

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

其他回答

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

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

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

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

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

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

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

从iOS 4.1开始,有了一种使用自定义字体的新方法。它允许你动态加载字体,从文件中包含的应用程序,下载的数据,或你有什么。它还可以让你在需要的时候加载字体,而旧的方法是在应用启动时加载它们,如果你有很多字体,这可能会花费很长时间。

新方法在ios-dynamic-font-loading中描述

使用CTFontManagerRegisterGraphicsFont函数,给它一个带有字体数据的缓冲区。然后它就可以用于UIFont和web视图,就像旧的方法一样。下面是该链接的示例代码:

NSData *inData = /* your font-file data */;
CFErrorRef error;
CGDataProviderRef provider = CGDataProviderCreateWithCFData((CFDataRef)inData);
CGFontRef font = CGFontCreateWithDataProvider(provider);
if (! CTFontManagerRegisterGraphicsFont(font, &error)) {
    CFStringRef errorDescription = CFErrorCopyDescription(error)
    NSLog(@"Failed to load font: %@", errorDescription);
    CFRelease(errorDescription);
}
CFRelease(font);
CFRelease(provider);

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

遵循这个步骤

1)在项目中复制你的字体

2)以源代码模式打开你的.plist文件…(注意-不要打开info.plist)

3)在此之前-右键单击你的字体,在fontforge或类似的编辑器中打开它,并将其安装到你的系统中,它应该是安装的

4)类型

 <key>UIAppFonts</key>
<array>
    <string>MyriadPro.otf</string>
</array>

5)在你的类中输入这个代码。m

 [lblPoints setFont:[UIFont fontWithName:@"Myriad Pro" size:15.0]];

这里lblPoints将改变你的UILabel

完成了! ! 如果你的字体仍然不能工作,首先检查你的字体兼容性