Cocos2d-x 3.9教程:6. 文字的显示

来源:互联网 发布:迪杰斯特拉算法讲解 编辑:程序博客网 时间:2024/05/18 23:26

6. 文字的显示

在cocos2d-X中,我们可以用Label来在相应的位置显示字符串,但由于我们在windows下使用VS2013之类的工具时,默认对汉字的处理都是非UTF-8字符的,所以即便我们工程的选项设定为UTF-8,汉字也是无法正常显示的。

如:auto label = Label::createWithTTF("美好的一天", "fonts/abc.ttf", 24);

    

    // position the label on the center of the screen

    label->setPosition(Vec2(origin.x + visibleSize.width/2,

                            origin.y + visibleSize.height - label->getContentSize().height));

 

    // add the label as a child to this layer

    this->addChild(label, 1)

字符串"美好的一天",在windows上直接运行时是显示不出来的,因此我们按照网上的处理方式,把字符串先转成UTF-8的,再传入就可以显示出来了。

Windows下GB2312转UTF-8的代码为:

char * G2U(const char* gb2312)

{

int len = MultiByteToWideChar(CP_ACP, 0, gb2312, -1, NULL, 0);

wchar_t* wstr = new wchar_t[len + 1];

memset(wstr, 0, len + 1);

MultiByteToWideChar(CP_ACP, 0, gb2312, -1, wstr, len);

len = WideCharToMultiByte(CP_UTF8, 0, wstr, -1, NULL, 0, NULL, NULL);

char* str = new char[len + 1];

memset(str, 0, len + 1);

WideCharToMultiByte(CP_UTF8, 0, wstr, -1, str, len, NULL, NULL);

if (wstr) delete[] wstr;

return str;

}

那么在使用时,代码修改为:

auto label = Label::createWithTTF(G2U("美好的一天"),"fonts/abc.ttf", 24);

一定要注意:但在生成APK文件时,请还原为原来的方式,上面的方法仅针对windows平台VS运行exe时看不到中文的问题!

0 0
原创粉丝点击