您的位置:首页 > 移动开发 > Cocos引擎

【Cocos2dx】中文乱码问题

2015-09-02 11:51 429 查看
Cocos2dx的中文乱码问题,造成原因是VS将其以GBK编译,而Cocos2dx本身的引擎是UTF-8,所以非西欧字符会出现乱码。谁让cocos2d-x是由cocos2d而来,而cocos2d这东西是老外写的呢?引擎的编写者根本没有考虑这点。

解决的方式有很多种,比如在VS写一段转码函数,引入Cocos2dx的iconv库,但这都不是好方法,主流的解决方法是将中文字符串写到UTF-8编码的XML文件中,然后仿照Android中的strings.xml解析XML文件,而且这种方法还方便以后的国际化、跨平台编译。

首先在工程目录下的资源文件夹Resources,新建一个字符文件strings.xml,以后编写Cocos2dx的时候,养成写安卓的习惯,把所有字符藏在这个strings.xml之中。Cocos2dx的资源文件夹在《【Cocos2dx】资源文件夹,播放背景音乐,导入外部库》(点击打开链接)已经说了,这里不再赘述。

例如如下的一段strings.xml代码:

<dict>
    <key>HelloWorldString</key>
    <string>你好,世界</string>
</dict>


如下图,记得,以UTF-8的编码形式保存,Windows下的记事本默认编码是ANSI。



之后在Cocos2dx通过如下形式,读取这个strings.xml,加载一个一个key标签下对应的字符串string

//利用CCDictionary来读取xml  
	CCDictionary *strings = CCDictionary::createWithContentsOfFile("strings.xml");//载入资源文件夹的strings.xml
	//读取HelloWorld键中的值objectForKey根据key,获取对应的string  
	const char *HelloWorld = ((CCString*)strings->objectForKey("HelloWorldString"))->m_sString.c_str();
如上的代码,就是将HelloWorldString这个key对应的String,读入到HelloWorld这个字符指针中。毕竟C++没有原生的String。只能用const char *HelloWorld来指向“你好,世界”这个字符。
#include "HelloWorldScene.h"

USING_NS_CC;

CCScene* HelloWorld::scene()
{
// 'scene' is an autorelease object
CCScene *scene = CCScene::create();

// 'layer' is an autorelease object
HelloWorld *layer = HelloWorld::create();

// add layer as a child to scene
scene->addChild(layer);

// return the scene
return scene;
}

// on "init" you need to initialize your instance
bool HelloWorld::init()
{
//利用CCDictionary来读取xml CCDictionary *strings = CCDictionary::createWithContentsOfFile("strings.xml");//载入资源文件夹的strings.xml //读取HelloWorld键中的值objectForKey根据key,获取对应的string const char *HelloWorld = ((CCString*)strings->objectForKey("HelloWorldString"))->m_sString.c_str();

//获取屏幕的尺寸、位置信息等
CCSize visibleSize = CCDirector::sharedDirector()->getVisibleSize();

//乱码文字
CCLabelTTF *label0 = CCLabelTTF::create("你好,世界","arial",72);
label0->setPosition(ccp(visibleSize.width/2,2*visibleSize.height/3));
this->addChild(label0);

//正常中文
CCLabelTTF *label1 = CCLabelTTF::create(HelloWorld,"arial",72);
label1->setPosition(ccp(visibleSize.width/2,visibleSize.height/3));
this->addChild(label1);
return true;
}

void HelloWorld::menuCloseCallback(CCObject* pSender)
{
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT) || (CC_TARGET_PLATFORM == CC_PLATFORM_WP8)
CCMessageBox("You pressed the close button. Windows Store Apps do not implement a close button.","Alert");
#else
CCDirector::sharedDirector()->end();
#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
exit(0);
#endif
#endif
}


如上的代码,如果将“你好,世界”生成CCLabelTTF直接输出,则会是乱码,如果将“你好,世界”从资源文件夹Resources下的strings.xml,这个编码为UFT-8的文件读入到const char *HelloWorld,再生成CCLabelTTF输出,是没有问题的。如下图所示:



这样,通过strings.xml还能使跨平台编译、国际化变得非常方便。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: