除了前面介紹的兩種方法外,還有一種直接在代碼中轉碼的方法來顯示中文,但我並不推薦,前面的兩種方法更爲穩定。即便如此,我們也來介紹一下。首先,我們新建一個工程,命名爲FontTest,然後修改init函數如下:
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);
//創建顯示文本
CCLabelTTF * label=CCLabelTTF::create(FontToUTF8("這是“微軟雅黑”字體類型的HelloWorld"),"微軟雅黑",32);
//獲取屏幕大小
CCSize size=CCDirector::sharedDirector()->getWinSize();
//設置文本大小和顏色
label->setPosition(ccp(size.width/2,size.height/2));
label->setColor(ccGREEN);
//添加進佈景
addChild(label,1);
bRet = true;
} while (0);
return bRet;
}
我們還要在HelloWorld.h文件裏聲明用到的字符編碼轉換方法FontToUTF8,添加如下代碼:
char* FontToUTF8(const char* font);
然後在.cpp文件的最後實現此方法:
char* HelloWorld::FontToUTF8(const char* font)
{
int len=MultiByteToWideChar(CP_ACP,0,font,-1,NULL,0);
wchar_t* wstr=new wchar_t[len+1];
memset(wstr,0,len+1);
MultiByteToWideChar(CP_ACP,0,font,-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;
}
好了,運行,效果如下: