cocos2d-x 实现中文输出

上一篇我们实现了场景的切换,下面讲讲cocos2d-x实现中文输出吧,可能刚开始会发现,把标签的 HelloWorld 换成中文的时候会出现乱码

下面我们来说说如何实现中文输出吧!

首先,个人觉得可以新建一个tools.cpp 和 tools.h 文件

首先在tools.h:

#ifndef _TOOLS_H_ //预定义块

#define  _TOOLS_H_

#include "cocos2d.h"

#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)

#include "iconv.h" //注意这里可能好多同学不能导入这个文件,需要在项目里面进行设置 待会儿再讲

#endif

#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) //字符转换,使cocos2d-x在win32平台支持中文显示

int GBKToUTF8(std::string &gbkStr,const char* toCode,const char* formCode);//定义一个进行字符转换的函数

#endif

#endif //_TOOLS_H_

这样我们在tools.h里面的代码就over了 很少吧

 

下面就是如何实现这个函数了

在tools.cpp文件中

#include "tools.h"

#include "iconv.h"

#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) //字符转换,使cocos2d-x在win32平台支持中文显示

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;

}

#endif

//具体代码的含义还在进一步探讨中!

这样我们就完成了声明和定义转换的函数了

下面就是如何在屏幕上显示了,即完成转化

其实就是一个标签或者菜单前的一个调用函数:

例如在 HelloWorldScene里面输出HelloWorld改成输出:你好

 

CCSize size = CCDirector::sharedDirector()->getWinSize();

std::string title = "你好”;

#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
 GBKToUTF8(title,"gb2312","utf-8");
#endif

CCLabelTTF *pLabel = CCLabelTTF::labelWithString(title.c_str(),"Thonburi",30);

pLabel->setPosition(ccp(size.width / 2, size.height*0.9f));

this->addChild(pLabel,1);

这样实现中文输出就over 了  哈哈 很简单吧!!!

待续。。。。

posted @ 2012-04-08 15:19  EWen.流  阅读(690)  评论(0编辑  收藏  举报