首先,推荐大家读一下http://blog.csdn.net/wm_jiangnanan/article/details/8665040这篇文章[1]
然后,看一下 【cocos目录/cocos2dx/platform/ios/CCImage.mm】这个文件。
在static bool _initWithString(const char * pText, cocos2d::CCImage::ETextAlign eAlign, const char * pFontName, int nSize, tImageInfo* pInfo)函数中,我们能找到注释:
// On iOS custom fonts must be listed beforehand in the App info.plist (in order to be usable) and referenced only the by the font family name itself when
// calling [UIFont fontWithName]. Therefore even if the developer adds 'SomeFont.ttf' or 'fonts/SomeFont.ttf' to the App .plist, the font must
// be referenced as 'SomeFont' when calling [UIFont fontWithName]. Hence we strip out the folder path components and the extension here in order to get just
// the font family name itself. This stripping step is required especially for references to user fonts stored in CCB files; CCB files appear to store
// the '.ttf' extensions when referring to custom fonts.
大概意思是我们在ios上必须使用字体的[family name],那么下一步就是如何获知字体的family name
在文章[1]中,作者提出了新建一个cocos2d工程,这其实没必要,因为
NSArray *familyNames = [[NSArray alloc] initWithArray:[UIFont familyNames]];//获得所有系统可用字体 及 info.plist中添加的字体
NSArray *fontNames;
NSInteger indFamily, indFont;
for (indFamily=0; indFamily<[familyNames count]; ++indFamily)
{
NSLog(@"Family name: %@", [familyNames objectAtIndex:indFamily]);//遍历并输出这些字体
// fontNames = [[NSArray alloc] initWithArray://下面的代码其实没意义,因为咱们只要获知family name就可以了
// [UIFont fontNamesForFamilyName:
// [familyNames objectAtIndex:indFamily]]];
//for (indFont=0; indFont<[fontNames count]; ++indFont)
//{
// NSLog(@" Font name: %@", [fontNames objectAtIndex:indFont]);
// }
//[fontNames release];
}
[familyNames release];
建立cocos2d工程是为了运行上述这段代码,而这段代码在cocos2d-x工程里也是可以运行的,因为ios模板创建的时候自带了两个.mm文件
在AppController.mm的- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions函数里,添加上述代码
在获知了将要使用的中文字体的familyname之后,我们将原来的字体名替换成familyname即可
举例:
CCLabelTTF *labelChinese = CCLabelTTF::create("测试中文", "这里填入字体的family name", 22);