问题及处理方案:
一、Cocos2d-x 引擎编码格式默认为utf8,而VS开发环境默认为gbk2312,如修改编码保存格式为utf8,可以暂时解决乱码,但存在编译时错误,这跟输出的字符个数有关。
(解决方案:如报错可以在字符串后加一个字符来解决!) Cocos2d-x引擎文档说可以在最后补后 一个啊 字符串。
二、可以从utf8的文件中读取字符来解决,这个方案网络都可以搜到。
好处:可以有效的国际化客户端,如翻译成多版本客户,只需要把utf8 格式文件提供出来,对比翻译就OK了。
三、利用boost库来解决乱码问题,以处理跨平台问题。
boost::locale相关说明文档以及示例:http://blog.csdn.net/leitianjun/article/details/24658655
我主要做了如下简单封装:
1、在VS开发工程中包含boost目录。
2、在VS开发工程中包含boost的lib库目录。如下图所示
3、保存以下代码为示例文件,并添加到工程
//Boost_Tools.h
#ifndef __BOOST_TOOLS_H__ #define __BOOST_TOOLS_H__ #include <boost/locale.hpp> namespace boosttoolsnamespace { class CBoostTools { public: //封装 string between( string const &text,string const &to_encoding, //string const &from_encoding,method_type how = default_method); //直接处理gbk转utf8编码 static std::string gbktoutf8(std::string const &text); //直接处理utf8转gbk static std::string utf8togbk(std::string const &text); //直接处理big5转utf8 static std::string big5toutf8(std::string const &text); //直接处理utf8转big5 static std::string utf8tobig5(std::string const &text); }; } #endif
//Boost_Tools.cpp #include "Boost_Tools.h" using namespace boost::locale::conv; //直接处理gbk转utf8编码 std::string boosttoolsnamespace::CBoostTools::gbktoutf8(std::string const &text) { //"UTF-8", "GBK" std::string const &to_encoding("UTF-8"); std::string const &from_encoding("GBK"); method_type how = default_method; return boost::locale::conv::between(text.c_str(), text.c_str() + text.size(), to_encoding, from_encoding, how); } //直接处理utf8转gbk std::string boosttoolsnamespace::CBoostTools::utf8togbk(std::string const &text) { std::string const &to_encoding("GBK"); std::string const &from_encoding("UTF-8"); method_type how = default_method; return boost::locale::conv::between(text.c_str(), text.c_str() + text.size(), to_encoding, from_encoding, how); } //直接处理big5转utf8 std::string boosttoolsnamespace::CBoostTools::big5toutf8(std::string const &text) { std::string const &to_encoding("UTF-8"); std::string const &from_encoding("BIG5"); method_type how = default_method; return boost::locale::conv::between(text.c_str(), text.c_str() + text.size(), to_encoding, from_encoding, how); } //直接处理utf8转big5 std::string boosttoolsnamespace::CBoostTools::utf8tobig5(std::string const &text) { std::string const &to_encoding("BIG5"); std::string const &from_encoding("UTF-8"); method_type how = default_method; return boost::locale::conv::between(text.c_str(), text.c_str() + text.size(), to_encoding, from_encoding, how); }
4、Cocos2d-x中的代码示例如下:
//别忘了包含头文件#include Boost_Tools.h //直接给create函数传参就行了,如:boosttoolsnamespace::CBoostTools::gbktoutf8("开始游戏") auto label1 = LabelBMFont::create(boosttoolsnamespace::CBoostTools::gbktoutf8("开始游戏"), "fonts/Bitmapstartmenu.fnt"); label1->setPosition(Point(origin.x + visibleSize.width / 2, origin.y + visibleSize.height - label1->getContentSize().height)); label1->setColor(Color3B(255, 255, 0)); this->addChild(label1,2)