Cocos2d-win32平台下中文乱码问题解决方案
原因:Windows中文环境采用的是GBK编码,源程序文件默认也是GBK编码。
解决方案:使用配置方式读取中文字。
只有在Windows平台下才会出现这种问题,Android和IOS不会出现这个问题。
解决方案
引入cJson开源库,通过读取utf-8编码格式的json文件进行显示。
效果展示
源码如下
json文件
HelloWorldScene.h
#ifndef __HELLOWORLD_SCENE_H__
#define __HELLOWORLD_SCENE_H__
#include "cocos2d.h"
//引入string库
#include <string>
//引入cJson库文件
#include "cJSON.h"
class HelloWorld : public cocos2d::Scene
{
public:
static cocos2d::Scene* createScene();
virtual bool init();
// implement the "static create()" method manually
CREATE_FUNC(HelloWorld);
private:
//记录当前文字内容
std::string prt_content;
cocos2d::Label* prt_label;
};
#endif // __HELLOWORLD_SCENE_H__
HelloWorldScene.cpp
#include "HelloWorldScene.h"
#include "SimpleAudioEngine.h"
USING_NS_CC;
using namespace std;
Scene* HelloWorld::createScene()
{
return HelloWorld::create();
}
// Print useful error message instead of segfaulting when files are not there.
static void problemLoading(const char* filename)
{
printf("Error while loading: %s\n", filename);
printf("Depending on how you compiled you might have to add 'Resources/' in front of filenames in HelloWorldScene.cpp\n");
}
// on "init" you need to initialize your instance
bool HelloWorld::init()
{
if (!Scene::init())
return false;
auto visibleSize = Director::getInstance()->getVisibleSize();
Vec2 origin = Director::getInstance()->getVisibleOrigin();
//读取json文件内容
FILE* pFile = fopen("test.json", "r");
if (nullptr == pFile)
{
problemLoading("test.json");
return false;
}
char testContent[1024 * 20]{ 0 };
while (!feof(pFile))
{
char buffer[1024]{ 0 };
fgets(buffer, 1024, pFile);
int index = strlen(testContent);
for (int i = 0; i < strlen(buffer); i++)
{
if (buffer[i] == '\n')
break;
testContent[index++] = buffer[i];
}
}
//通过cJson库解析读取内容
cJSON* monitor = cJSON_Parse(testContent);//将字符串转成cJson对象
if (nullptr == monitor)
return false;
//获取key为mainKey1的内容
cJSON* mainKey1 = cJSON_GetObjectItem(monitor, "mainKey1");
//获取key为value的内容
auto value1 = cJSON_GetObjectItem(mainKey1, "value");
//输出查看结果
log(value1->valuestring);
//实现背景图片
auto sprite = Sprite::create("1.jpg");
sprite->setAnchorPoint(Vec2::ANCHOR_MIDDLE);
sprite->setPosition(Vec2(visibleSize / 2));
sprite->setScale(0.3);
this->addChild(sprite);
//显示文字内容
prt_content = value1->valuestring;
//开始不显示任何内容
prt_label = Label::create(prt_content, "方正姚体", 30);
prt_label->setAnchorPoint(Vec2::ANCHOR_MIDDLE);
prt_label->setPosition(Vec2(visibleSize / 2));
prt_label->setColor(Color3B(248, 248, 255));
prt_label->enableBold();
prt_label->setDimensions(400.0f, 0);//使用纯英文换行失效,只有存在中文才可能生效!该属性用于实现自动换行
this->addChild(prt_label);
return true;
}
TIPS:setDimensions使用英文可能失效,这是引擎级别的bug,从Cocos官方论坛得知该结论。
Cocos2d-win32平台下中文乱码问题解决方案_cocos2d中文_ufgnix0802的博客-CSDN博客](ufgnix0802.blog.csdn.net/article/det…)
开启掘金成长之旅!这是我参与「掘金日新计划 · 2 月更文挑战」的第 10 天, 点击查看活动详情