Cocos2dx 中文乱码的解决方法
问题与解决方法 在windows环境下使用visual studio 开发cocos2d-x,由于visual studio 默认编码为GBK 格式,而cocos2d-x引擎默认编码为UTF-8, 如果有用到中文,在游戏运行时有可能会出现乱码的情况,这个问题一般有三种解决方案,如下 1、将源码文件保存为utf-8格式(不建议,治标不治本) 2、自己编写编码转换代码,或者使用Cocos2dx的库。 使用iconv,引擎也提供了这个库,不过只是win32平台,移植到android上还得自己去下载iconv库编译。 3、将显示文本单独保存为文本文件(该文件编码为utf-8),由系统统一模块管理文本读取显示,建议使用这种方式,便于后期系统维护,并实现国际化。(推荐) strings.plist http://www.52php.cn/article/p-xmwozrmr-bbh.html 把字符串写到xml文件中,然后解析xml文件,格式按照android中的strings.xml。这是一种更好的做法,特别是需要提供国际化支持时。 http://www.52php.cn/article/p-xtzexrzy-bkb.html 缺点: 方法一:可能导致其它未知错误。 方法二:win32和Android都需要转换,而且编码转换库会使安卓apk变大。 方法三:虽然实现有点麻烦,但是是较完善的解决方法。
cocos2d-x3.0从XML读取中文转载自:http://www.xuebuyuan.com/1482775.html 保存的XML文件放到resources文件夹里,具体格式自己定,但要是uft8的。比如:
<pre name="code" class="html"><?xml version="1.0" encoding="utf-8"?> <dict> <key>shop_info1</key> <string>猛犸</string> <key>shop_info2</key> <string>慢慢</string> </dict> 解析代码也很少: <pre name="code" class="cpp">// 解析xml获取值 CCDictionary* strings = CCDictionary::createWithContentsOfFile("String.xml"); // xml文件加载为CCDictionary对象 const char *shop_info1 = ((String*)strings->objectForKey("shop_info1"))->getCString(); // 通过键来获取值 经过验证,cocos3.2版本的也能运行。 不过CCDictionary是cocos2.x版本的数据结构,3.x版本较少使用。
官网解析xml方法 Cocos2d-x 已经加入了tinyxml2用于xml的解析。3.0版本位于external/tinyxml2下。2.x版本位于cocos2dx/support/tinyxml2下。 引入头文件#include "tinyxml2/tinyxml2.h" using namespace tinyxml2; xml解析 void HelloWorld::parseXML(const char *fileName) { std::string filePath = FileUtils::getInstance()->getWritablePath() + fileName; XMLDocument *pDoc = new XMLDocument(); XMLError errorId = pDoc->LoadFile(filePath.c_str()); if (errorId != 0) { //xml格式错误 return; } XMLElement *rootEle = pDoc->RootElement(); //获取第一个节点属性 const XMLAttribute *attribute = rootEle->FirstAttribute(); //打印节点属性名和值 log("attribute_name = %s,attribute_value = %s",attribute->Name(),attribute->Value()); XMLElement *dicEle = rootEle->FirstChildElement("dic"); XMLElement *keyEle = dicEle->FirstChildElement("key"); if (keyEle) { log("keyEle Text= %s",keyEle->GetText()); } XMLElement *arrayEle = keyEle->NextSiblingElement(); XMLElement *childEle = arrayEle->FirstChildElement(); while ( childEle ) { log("childEle Text= %s",childEle->GetText()); childEle = childEle->NextSiblingElement(); } delete pDoc; } 在节点解析过程中,注意对获取到的节点进行判空处理。 解析结果打印 cocos2d: attribute_name = version,attribute_value = 1.0 cocos2d: keyEle Text= Text cocos2d: childEle Text= Cocos2d-x cocos2d: childEle Text= Cocos2d-x cocos2d: childEle Text= Cocos2d-x (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |