多一分钟学习,早一秒钟提高

VC++、C++、Socket、DirectUI、wxWidgets、Cocos2d-x、CocosCreator、Unity3D、UE4、ThinkPHP
posts - 32, comments - 12, trackbacks - 0, articles - 0
  C++博客 :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

Cocos2d-x 中文显示

Posted on 2014-04-13 13:52 虚空骄阳 阅读(690) 评论(0)  编辑 收藏 引用 所属分类: Cocos2d-x
一、使用第三方库iconv
bool IConvConvert(const char *from_charset, const char *to_charset, const char *inbuf, int inlen, char *outbuf, int outlen) 

{

iconv_t cd = iconv_open(to_charset, from_charset);

if (cd == 0) return false;

const char **pin = &inbuf;

char **pout = &outbuf;

memset(outbuf,0,outlen);

size_t ret = iconv(cd,pin,(size_t *)&inlen,pout,(size_t *)&outlen);

iconv_close(cd);

return ret == (size_t)(-1) ? false : true;

}

std::string IConvConvert_GBKToUTF8(const std::string& str)

{

const char* textIn = str.c_str();

char textOut[256];

bool ret = IConvConvert("gb2312", "utf-8", textIn, strlen(textIn),textOut, 256);

return ret ? string(textOut) : string();

}
使用方法:
std::string text = IConvConvert_GBKToUTF8("我是中文字符串");

CCLabelTTF* pLabel = CCLabelTTF::labelWithString(text.c_str(), "Arial", 24);

二、使用XML文件
(通过读取xml文件显示中文,这种方法更利于软件的国际化)
1、先写好一个xml文件(CHN_Strings.xml)。注意记得要以UTF-8编码保存。格式很简单,一个key对应一个string的键值对。如下:
<dict>  
    <key>language</key>  
    <string>English</string>  
    <key>username</key>  
    <string>虚空骄阳</string>  
    <key>website</key>  
    <string>http://www.cppblog.com/xkjy3000/</string>  
</dict>
2、通过CCDictionary读取xml
(CCDictionary其实是利用哈希表算法来进行CCObject管理的一个类)
A、创建词典类实例
CCDictionary *pchStrings = CCDictionary::createWithContentsOfFile("CHN_Strings.xml");
B、通过键(key)获取值(value)
const char *pUsername = ((CCString*)pchStrings->objectForKey("username"))->m_sString.c_str();
C、使用value
CCLabelTTF* pLabel = CCLabelTTF::create(pUsername, "Arial", 24);      //这里创建一个文本  
pLabel->setPosition(ccp(origin.x + visibleSize.width/2,origin.y + visibleSize.height - pLabel->getContentSize().height));  
this->addChild(pLabel, 1);

以下自定义读取指定xml中指定key中文字符串的函数
函数声明
static const char* getCHString(const string filename, const string key);
函数实现
const char* XXX::getCHString(const string filename, const string key)
{  
    //利用CCDictionary来读取xml
    CCDictionary *pStrings = CCDictionary::createWithContentsOfFile(filename.c_str());
    //读取key键中的值 objectForKey根据key,获取对应的string
    const char *pStr = ((CCString*)pStrings->objectForKey(key))->m_sString.c_str();
    return pStr;
}

使用方法:
const char* pText = XXX::getCHString("CHN_Strings.xml", "username");

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理