本篇讲在cocos2d-x中制作标签和菜单
各种字符串之间的转换
首先引入Cocos2d-x中的三种字符串,各种字符串之间的转换有点繁琐,很多情况下需要根据函数字符串参数的格式来进行字符串转换。
-
const char是C风格的字符串, char表示字符串, 加上const表示指针是不可变的(字符串首地址是地址常量)。
-
std::string是C++风格的字符串,它底层封装了const char*。
-
cocos2d::__String是cocos2d-x引擎的字符串。
log()使用的字符串必须是char*类型。
1.std::string转化为const char*:
std::string name = "lulu";
std::string name2 = std::string("lulu2");
std::string* name3 = new std::string("lulu3");
const char* cstring = name.c_str();
const char* cstring2 = name2.c_str();
const char* cstring3 = name3->c_str();
log("%s, %s, %s", cstring, cstring2, cstring3);
输出:lulu, lulu2, lulu3
2.const char* 和std::string转化为cocos2d::__String
const char* cstring = "lulu";
std::string string = "lulu2";
__String *name = __String::createWithFormat("%s", cstring);
/*实际上是先把c++字符串转化为c字符串,然后转化为cocos中的字符串*/
__String *name2 = __String::createWithFormat("%s", string.c_str());
/*最后log()调试需要再转c字符串*/
log("%s, %s", name->getCString(), name2->getCString());
输出:lulu, lulu2
使用标签
三种旧标签:
LabelTTF基于系统字体
Label Atlas 基于图集的标签
LabelBMFont是位图字体标签,图配有坐标
Cocos2d-x 3.x坐标类Label:
- 使用系统字体
static Label* createWithSystemFont(const std::string &text,const std::string& font, float fontSize)
- 非系统字体
static Label* createWithTTF(const std::string & text,const std::string & fontFile, float fontSize)
可以指定一些配置,只能针对TTF字体
static Label* createWithTTF(const TTFConfig& ttfConfig,
const std::string& text)
- 跟LabelBMFont相似
局限性是只有位图上的符号,不适用于显示中文。
static Label* createWithBMFont(const std::string& bmfontFilePath,const std::string& text)
示例:
//使用系统字体create label,使用代码解决中文乱码问题,代码在超链接中
auto label1 = Label::createWithSystemFont(MyUtility::gbk_2_utf8("咏菊"), "Cambria", 62);
label1->setPosition(Vec2(origin.<