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

cocos 中文字符显示问题

2016-03-09 08:52 471 查看
在学习使用cocos中,经常会出现中文字符无法显示问题,在windows上,最简单的就是把带有中文字符的页面保存为utf-8




编译一下就可以看到中文字符的乱码消失了。

cocos在安卓平台下需要把unicode 转换成utf-8编码,一下提供一个转换函数

class Tools{
static void WStrToUTF8(std::string& dest, const std::wstring& src){
dest.clear();
for (size_t i = 0; i < src.size(); i++){
wchar_t w = src[i];
if (w <= 0x7f){
dest.push_back((char)w);
}
else if (w <= 0x7ff){
dest.push_back(0xc0 | ((w >> 6) & 0x1f));
dest.push_back(0x80 | (w & 0x3f));
}
else if (w <= 0xffff){
dest.push_back(0xe0 | ((w >> 12) & 0x0f));
dest.push_back(0x80 | ((w >> 6) & 0x3f));
dest.push_back(0x80 | (w & 0x3f));
}
else if (sizeof(wchar_t) > 2 && w <= 0x10ffff){
dest.push_back(0xf0 | ((w >> 18) & 0x07)); // wchar_t 4-bytes situation
dest.push_back(0x80 | ((w >> 12) & 0x3f));
dest.push_back(0x80 | ((w >> 6) & 0x3f));
dest.push_back(0x80 | (w & 0x3f));
}
else{
dest.push_back('?');
}
}
}
public:

static std::wstring StringToWString(const std::string &str)
{

wchar_t buf[128];
#ifdef WIN32
setlocale(LC_CTYPE, "");
#endif
mbstowcs(buf, str.c_str(), 10);
std::wstring wstr(buf);

return wstr;
}
static std::string FontToUTF8(const std::wstring& str){
std::string result;
WStrToUTF8(result, str);
return result;
}

static std::string FontToUTF8(const std::string& str){
std::string result;
auto s = StringToWString(str);
WStrToUTF8(result,s );
return result;
}
};


直接在要使用中文字符的地方使用FontToUTF8();
在部分手机上要使用FontToUTF8(L"中文字符");才能显示
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: