在上一篇《cocos2d-x显示中文,方法(1)》中,我们使用官方TestCpp里面的方法,通过xml文件实现了显示中文。那么还有其他的方法吗?当然有了,那就是使用第三方类库。
coco2d-x自带了libiconv.lib类库来支持中文,那么我们就来学习一下怎么使用它,这里参考了老G前辈的方法。
#ifndef __TOOLS_H__ #define __TOOLS_H__ #include "cocos2d.h" #include "iconv.h" int GBKToUTF8(std::string &gbkStr,const char* toCode,const char* formCode); #endif
#include "tools.h" int GBKToUTF8(std::string &gbkStr,const char* toCode,const char* formCode) { iconv_t iconvH; iconvH = iconv_open(formCode,toCode); if(iconvH==0){ return -1; } const char* strChar=gbkStr.c_str(); const char** pin=&strChar; size_t strLength=gbkStr.length(); char* outbuf=(char*)malloc(strLength*4); char* pBuff=outbuf; memset(outbuf,0,strLength*4); size_t outLength = strLength*4; if(-1==iconv(iconvH,pin,&strLength,&outbuf,&outLength)){ iconv_close(iconvH); return -1; } gbkStr=pBuff; iconv_close(iconvH); return 0; }
bool HelloWorld::init() { bool bRet = false; do { ////////////////////////////////////////////////////////////////////////// // super init first ////////////////////////////////////////////////////////////////////////// CC_BREAK_IF(! CCLayer::init()); ////////////////////////////////////////////////////////////////////////// // add your codes below... ////////////////////////////////////////////////////////////////////////// // 1. Add a menu item with "X" image, which is clicked to quit the program. // Create a "close" menu item with close icon, it's an auto release object. CCMenuItemImage *pCloseItem = CCMenuItemImage::create( "CloseNormal.png", "CloseSelected.png", this, menu_selector(HelloWorld::menuCloseCallback)); CC_BREAK_IF(! pCloseItem); // Place the menu item bottom-right conner. pCloseItem->setPosition(ccp(CCDirector::sharedDirector()->getWinSize().width - 20, 20)); // Create a menu with the "close" menu item, it's an auto release object. CCMenu* pMenu = CCMenu::create(pCloseItem, NULL); pMenu->setPosition(CCPointZero); CC_BREAK_IF(! pMenu); // Add the menu to HelloWorld layer as a child layer. this->addChild(pMenu, 1); CCSize size = CCDirector::sharedDirector()->getWinSize(); std::string hello="你好"; GBKToUTF8(hello,"gb2312","utf-8"); CCLabelTTF* label=CCLabelTTF::create(hello.c_str(),"Arial",20); label->setPosition(ccp(size.width/2,size.height*0.5f)); this->addChild(label,2); // 3. Add add a splash screen, show the cocos2d splash image. CCSprite* pSprite = CCSprite::create("HelloWorld.png"); CC_BREAK_IF(! pSprite); // Place the sprite on the center of the screen pSprite->setPosition(ccp(size.width/2, size.height/2)); // Add the sprite to HelloWorld layer as a child layer. this->addChild(pSprite, 0); bRet = true; } while (0); return bRet; }