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://blog.csdn.net/z309241990/article/details/26976619

把字符串写到xml文件中,然后解析xml文件,格式按照android中的strings.xml。这是一种更好的做法,特别是需要提供国际化支持时。

http://blog.csdn.net/zhanghefu/article/details/21288451

缺点:

方法一:可能导致其它未知错误。

方法二: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







  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值