开发平台是win32,定义了一个Ansi与Utf8转换的类AnsiUtf8,用以进行cocos2dx中的中文显示,类代码见下:
头文件:
#ifndef _ANSIUTF8_H_
#define _ANSIUTF8_H_
#include "cocos2d.h"
using namespace std;
class AnsiUtf8
{
public:
static string AnsiToUtf8(string strAnsi);
static string Utf8ToAnsi(string strUtf8);
};
#endif
```
源文件:
#include "AnsiUtf8.h"
string AnsiUtf8::AnsiToUtf8(string strAnsi)
{
string ret;
if (strAnsi.length() > 0)
{
int nWideStrLength = MultiByteToWideChar(CP_ACP, 0, strAnsi.c_str(), -1, NULL, 0);
WCHAR* pwszBuf = (WCHAR*)malloc((nWideStrLength + 1)*sizeof(WCHAR));
memset(pwszBuf, 0, (nWideStrLength + 1)*sizeof(WCHAR));
MultiByteToWideChar(CP_ACP, 0, strAnsi.c_str(), -1, pwszBuf, (nWideStrLength + 1)*sizeof(WCHAR));
int nUtf8Length = WideCharToMultiByte(CP_UTF8, 0, pwszBuf, -1, NULL, 0, NULL, FALSE);
char* pszUtf8Buf = (char*)malloc((nUtf8Length + 1)*sizeof(char));
memset(pszUtf8Buf, 0, (nUtf8Length + 1)*sizeof(char));
WideCharToMultiByte(CP_UTF8, 0, pwszBuf, -1, pszUtf8Buf, (nUtf8Length + 1)*sizeof(char), NULL, FALSE);
ret = pszUtf8Buf;
free(pszUtf8Buf);
free(pwszBuf);
}
return ret;
}
string AnsiUtf8::Utf8ToAnsi(string strUtf8)
{
std::string ret;
if (strUtf8.length() > 0)
{
int nWideStrLength = MultiByteToWideChar(CP_UTF8, 0, strUtf8.c_str(), -1, NULL, 0);
WCHAR* pwszBuf = (WCHAR*)malloc((nWideStrLength + 1)*sizeof(WCHAR));
memset(pwszBuf, 0, (nWideStrLength + 1)*sizeof(WCHAR));
MultiByteToWideChar(CP_UTF8, 0, strUtf8.c_str(), -1, pwszBuf, (nWideStrLength + 1)*sizeof(WCHAR));
int nAnsiStrLength = WideCharToMultiByte(CP_ACP, 0, pwszBuf, -1, NULL, 0, NULL, FALSE);
char* pszAnsiBuf = (char*)malloc((nAnsiStrLength + 1)*sizeof(char));
memset(pszAnsiBuf, 0, (nAnsiStrLength + 1)*sizeof(char));
WideCharToMultiByte(CP_ACP, 0, pwszBuf, -1, pszAnsiBuf, (nAnsiStrLength + 1)*sizeof(char), NULL, FALSE);
ret = pszAnsiBuf;
free(pszAnsiBuf);
free(pwszBuf);
}
return ret;
}
```
运用AnsiUtf8类:
修改游戏标题为中文:
glview = GLView::create(AnsiUtf8::AnsiToUtf8("我的游戏"));
```
在HelloWorld源文件的init函数中添加一个中文label:
auto label = LabelTTF::create(AnsiUtf8::AnsiToUtf8("中国人"), "fonts/叶根友爵宋体.ttf", 80);
label->setPosition(Point(visibleSize.width/6, visibleSize.height - label->getContentSize().height));
this->addChild(label, 1);
```
运行程序,结果正常:
然后,我想制作成apk应用程序,看中文能否显示,打开eclipse导入项目,修改mk文件,运行工程目录下的 build_native.py脚本文件,出错了,提示WCHAR等未声明:
我新人,求大神帮助,应该怎么做,才能解决这个问题?我没有用过xml等文件加载中文字符,感觉那样挺麻烦的!
