利用.plist文件让Cocos2d-x轻松支持多语言。
.plist文件类似于XML文件,下面是.plist文件的一个模版:
- <?xml version="1.0" encoding="UTF-8"?>
- <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
- <plist version="1.0">
- <dict>
- <key>tutorial_on</key>
- <string>Tutorial: ON</string>
- <key>tutorial_off</key>
- <string>Tutorial: OFF</string>
- </dict>
- </plist>
将不同语言保存在不同的.plist文件里,如下图:
然后在程序中要用到这些字符串的时候用以下宏调用:LocalizedCStringByKey(“tutorial_on”);,宏定义的完整代码如下:
- //Language.h
- using namespace cocos2d;
- //return type:const char*
- #define LocalizedCStringByKey(key) Language::getStringByKey(key)
- class Language{
- public:
- static const char* getStringByKey(const char * key){
- //获取当前系统环境语言类型
- ccLanguageType languageType = CCApplication::sharedApplication()->getCurrentLanguage();
- //字典
- CCDictionary *pDic;
- if(kLanguageChinese == languageType)
- //根据语言选择不同的属性表
- pDic = CCDictionary::createWithContentsOfFile("language/zh.plist");
- else
- pDic = CCDictionary::createWithContentsOfFile("language/en.plist");
- std::string keyStr = key;
- //返回key对应的value
- return (pDic -> valueForKey(keyStr))->getCString();
- }
- };