微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

【Cocos2d-X】中文乱码问题

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

Unicode转UTF-8函数

char* EncodetoUTF8(const char* mbcsstr)
{
    wchar_t*  wideStr;
    char*     utf8Str;
    int       charLen;
    charLen = MultiBytetoWideChar(936,0,mbcsstr,-1,NULL,0); 
    wideStr = (wchar_t*)malloc(sizeof(wchar_t)*charLen);
    MultiBytetoWideChar(936,wideStr,charLen);
    charLen = WideCharToMultiByte(CP_UTF8,NULL);
    utf8Str = (char*)malloc(charLen);
    WideCharToMultiByte(CP_UTF8,utf8Str,charLen,NULL);
    free(wideStr);
    return utf8Str;
}

使用示例:

cclabelTTF* pLabel = cclabelTTF::create(EncodetoUTF8("海贼王"),"Marker Felt",24);

    cclabelBMFont* label = cclabelBMFont::create(EncodetoUTF8("海贼王"),"fonts/_chapter7.fnt",24);

    // position the label on the center of the screen

    pLabel->setPosition(ccp(origin.x + visibleSize.width/2 -100,origin.y + visibleSize.height - pLabel->getContentSize().height));
    label->setPosition(ccp(origin.x + visibleSize.width / 2 + 100,origin.y + visibleSize.height - label->getContentSize().height));

    // add the label as a child to this layer
    this->addChild(pLabel,1);
    this->addChild(label,1);

效果图:

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐