cocos2d-x 中,字體文件需要保存在 fonts 文件夾中,如果字體路徑中沒有 fonts/ 會自動添加上這個文件夾。
如果字體名稱沒有 .ttf 后綴,也會自動加上這個后綴。
unsigned char* CCFreeTypeFont::loadFont(const char *pFontName, ssize_t *size) { std::string lowerCase(pFontName); std::string path(pFontName); for (unsigned int i = 0; i < lowerCase.length(); ++i) { lowerCase[i] = tolower(lowerCase[i]); } if (std::string::npos == lowerCase.find("fonts/")) { path = "fonts/"; path += pFontName; } if (std::string::npos == lowerCase.find(".ttf")) { path += ".ttf"; } std::string fullpath = FileUtils::getInstance()->fullPathForFilename(path.c_str()); return FileUtils::sharedFileUtils()->getFileData(fullpath.c_str(), "rb", size); }
string::npos 就是 -1, 表示沒有找到子串,find 方法用來查找字體名稱中是否包含了 fonts.