cocos2d-x的中文编码问题解决方案

最近在学习cocos2d-x,总结了一些开发遇到的问题,希望对和我一样的新手有所帮助。



bool IConvConvert(const char *from_charset, const char *to_charset, const char *inbuf, int inlen, char *outbuf, int outlen) 

{

    iconv_t cd = iconv_open(to_charset, from_charset);

if (cd == 0) return false;

const char **pin = &inbuf;

char **pout = &outbuf;

memset(outbuf,0,outlen);

size_t ret = iconv(cd,pin,(size_t *)&inlen,pout,(size_t *)&outlen);

iconv_close(cd);

return ret == (size_t)(-1) ? false : true;

}

std::string IConvConvert_GBKToUTF8(const std::string& str)

{

const char* textIn = str.c_str();

char textOut[256];

bool ret = IConvConvert("gb2312", "utf-8", textIn, strlen(textIn),textOut, 256);

return ret ? string(textOut) : string();

}

这是用 cocos2d-x的开发包内置了用于编码转换的iconv库来转化的。

使用:

std::string text = IConvConvert_GBKToUTF8("你好世界");

CCLabelTTF* pLabel = CCLabelTTF::labelWithString(text.c_str(), "Arial", 24);




inline void WStrToUTF8(std::string& dest, const 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('?');

}

}

自行转换


使用:

std::string text = WStrToUTF8(L"你好世界");

CCLabelTTF* pLabel = CCLabelTTF::labelWithString(text.c_str(), "Arial", 24);




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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值