【Cocos2d-X】中文乱码问题

前端之家收集整理的这篇文章主要介绍了【Cocos2d-X】中文乱码问题前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

初学Cocos就遇到了中文显示问题,在使用CCLabelTTF调用系统字体时,出现的是乱码;使用CCLabelBMFont调用自己设计的fnt文件时,就会什么都不显示百度了很久之后才明白,字体文件需要的中文得是UTF-8编码的,而项目又是Unicode,所以我们只需要把中文字符串的Unicode编码转化为UTF-8就行了。

Unicode转UTF-8函数

  1. char* EncodeToUTF8(const char* mbcsStr)
  2. {
  3. wchar_t* wideStr;
  4. char* utf8Str;
  5. int charLen;
  6. charLen = MultiByteToWideChar(936,0,mbcsStr,-1,NULL,0);
  7. wideStr = (wchar_t*)malloc(sizeof(wchar_t)*charLen);
  8. MultiByteToWideChar(936,wideStr,charLen);
  9. charLen = WideCharToMultiByte(CP_UTF8,NULL);
  10. utf8Str = (char*)malloc(charLen);
  11. WideCharToMultiByte(CP_UTF8,utf8Str,charLen,NULL);
  12. free(wideStr);
  13. return utf8Str;
  14. }

使用示例:

  1. CCLabelTTF* pLabel = CCLabelTTF::create(EncodeToUTF8("海贼王"),"Marker Felt",24);
  2.  
  3. CCLabelBMFont* label = CCLabelBMFont::create(EncodeToUTF8("海贼王"),"fonts/_chapter7.fnt",24);
  4.  
  5. // position the label on the center of the screen
  6.  
  7. pLabel->setPosition(ccp(origin.x + visibleSize.width/2 -100,origin.y + visibleSize.height - pLabel->getContentSize().height));
  8. label->setPosition(ccp(origin.x + visibleSize.width / 2 + 100,origin.y + visibleSize.height - label->getContentSize().height));
  9.  
  10. // add the label as a child to this layer
  11. this->addChild(pLabel,1);
  12. this->addChild(label,1);

效果图:

猜你在找的Cocos2d-x相关文章