Cocos2d-x学习笔记
Cocos2d-x中字符串
简介
在cocos中能使用的字符串有const char *
、std::string
、cocos2d::_String
等,其中const char *
是C风格的,std::string
是C++风格的,cocos2d::_String
才是cocos引擎提供的字符串类。
使用const char *
和std::string
std::stirng
是一个类,具有面向对象的优点,而const char *
不是。
初始化std::stirng
对象:
std::stirng name = "tony";
std::stirng name = std::string("tony");
使用std::stirng
不需要指针,也不需关心内存释放的问题。但也可以使用指针类型,但需要new关键字开辟内存空间,然后需要使用delete删除。
std::string *name = new std::string("tony");
delete name;
使用cocos2d::_String
创建该类型的主要静态函数create函数如下(使用create静态函数创建的对象不需要管理内存释放):
static _String * create(congst std::string &str)
static _String * createWithFormat(const char * format,...)
使用create函数的实例:
_String * name = _String::create("Hi, Tony");
int num = 123; _String * ns = _String::createWithFormat("% d", num);
数据类型装换实例:
cocos2d::_String
->const char *
:
_String * name = _String::create("Hi, Tony");
const char * cstring = name->getCString();
const char *
->cocos2d::_String
:
const char * cstring = "Hi, Tony";
_String * ns = _String::createWithFormat("% s", cstring);
std::string
->cocos2d::_String
:
std::string string = "Hi, Tony";
_String * ns = _String::createWithFormat("% s", string.c_str);
cocos2d::_String
->int
:
int num = 123;
_String * ns = _String::createWithFormat("% d", num);
int num2 = ns->intValue();
使用标签
标签:包括静态文字和动态文字,Cocos2d-x标签类有两种:Label和LabelAtlas。
静态文字:一般是由美工使用Photoshop绘制的图片,无法动态修改内容。
动态文字:通过程序访问,需要动态修改的内容。
使用Label类
Label类可以创建系统字体标签,TTF字体标签和位图字体标签。
使用Label类静态create函数如下:
static Label * createWithSystemFont(const std::string &text,//要显示的文字 const std::string& font,//系统字体名 float fontSize,//字体的大小 const Size& dimensions = Size::ZERO,//在屏幕上占据的区域大小,可以忽略 TextHAlignment hAlignment = TextHAlignment::LEFT,//文字横向对齐方式,可省略 TextVAlignment vAlignment = TextVAlignment::Top)//文字纵向对齐方式,可省略
static Label * createWithTTF(const std::string & text,//要显示的文字 const std::string, & fontFile,//字体文件 float fontSize,//字体的大小 const Size & dimensions = SIze::ZERO//在屏幕上占据的区域大小,可以忽略 TextHAlignment hAlignment = TextHAlignment::LEFT,//文字横向对齐方式,可省略 TextVAlignment vAlignment = TextVAlignment::Top)//文字纵向对齐方式,可省略
static Label * createWithTTF(const TTFConfig & ttfConfig, const std::string text, TextHAlignment hAlignment = TextHAlignment::LEFT, int maxLingWidth = 0)
static Label * createWithBMFont(const std::string& bmfontFilePath,//位图字体文件 const std::string& text,//要显示的内容 const TextHAlignment& alignment = TextHAlignment::LEFT,//文字横向对齐方式,可省略 int maxLIneWidth = 0,//可省略 const Vec2& imageOffset = Vec2::ZERO)//可省略
标签中文无法正常显示的问题
原因:Windows中文环境下使用Visula Studio创建的源文件是采用的GBK编码,而在Android和IOS下采用的UTF-8编码。
解决方法:
- 把HelloWorld.cpp文件另存为UTF-8格式,用记事本编辑工具
- VS工具中选择“菜单文件->高级保存”选项,选择Unicode(无签名)编码