cocos2dx引擎是老外开发的,采用UTF-8的编码格式,也没有考虑到中文的编码格式,所以显示中文会因为编码格式不一致而出现乱码。
如下面的代码:
CCLabelTTF* pLabel = CCLabelTTF::create("", "Arial", 30);
pLabel->setString("你好,世界!");
pLabel->setPosition(ccp(origin.x + visibleSize.width/2,
origin.y + visibleSize.height - pLabel->getContentSize().height));
this->addChild(pLabel, 1);
在HelloWorld::init中添加了上面的代码,编译运行,出现如下情况:
解决的办法有很多种如:对源文件cpp的编码改成UTF-8格式, 采用第三方库iconv 对字符编码进行转换、 用sqlite3 储存从sqlite中读取、 保存在xml文件中,从xml中读取等。我们这边采用xml 读取方法。 很简单;
1.在Rosource 目录底下右键创建一个.txt 的文件,如string.txt
2.将后缀名xml, 如string.xml
3.编写string.xml
<?xml version="1.0" encoding="UTF-8"?>
<String version="1.0">
<dict>
<key>hello_world</key>
<string>你好,世界!</string>
</dict>
</String>
这边的key 待会儿我们传入的值,获取出"你好,世界!"的中文
4. 在HelloWorld 中添加一个读取的接口
std::string HelloWorld::getStringFromXml(const char* key)
{
if (!key)
return "";
CCDictionary *pDictionary = CCDictionary::createWithContentsOfFile("string.xml");
std::string strText = ((CCString*)pDictionary->objectForKey(key))->m_sString;
return strText;
}
5.调用,看结果
CCLabelTTF* pLabel = CCLabelTTF::create("", "Arial", 30);
std::string strContent = this->getStringFromXml("hello_world"); //调用刚才所写的接口
pLabel->setString(strContent.c_str());
pLabel->setPosition(ccp(origin.x + visibleSize.width/2,
origin.y + visibleSize.height - pLabel->getContentSize().height));
this->addChild(pLabel, 1);
编译运行后,能正常显示了: