在使用 CCLabelTTF 时, 有时候我们需要对其进行换行操作,原有的换行操作函数只能固定的设置 CCLAbelTTF 矩形框的大小,有时候 不能够满足我们的需求。
看看,今天我们这里对 CClabelTTF 的处理吧 !!!
std::string str = "Dreams are one of those things that make you happy and going on !";
CCLabelTTF* m_label = CCLabelTTF::create(/*myWrap(*/str/*, 20)*/.c_str(), "Arial", 24);
m_label->setHorizontalAlignment(kCCTextAlignmentLeft);
m_label->setPosition(ccp(visibleSize.width/2, visibleSize.height/2));
this->addChild(m_label);
m_label->setDimensions(CCSize(200,200)); //设置 CCLabelTTF 矩形区域的大小
效果如下:
当让 ,我们给定大小并不是最好的方法。如果我们的字符串内容足够长,那我们怎么确定矩形区域的大小呢。
其实, 在使用 CClabelTTF 时, 我们会注意到,当我们在字符串中添加 " \n " 的时候,当其录入时碰到 " \n " 就会自动换行,根据这一特性,我们可以自己实现换行方法。
std::string HelloWorld::myWrap(std::string str, int length)
{
unsigned int beginPos = 0;
std::string resultStr;
std::vector<std::string > str_vec;
do
{
str_vec.push_back(str.substr(beginPos,length)); //substr函数将str中从beginPos到length之间的字符串截取,单独放入容器中
if (beginPos+length >str.size())
{
break; //当要截取的长度超出str的长度,则退出循环
}
else
{
beginPos += length;
}
} while (true);
for (unsigned int i = 0; i<str_vec.size(); ++i)
{
resultStr.append(str_vec.at(i)).append("\n"); //从容器逐一取出之前裁剪好的一段段字符串,分别在字符串后面加上换行符
}
resultStr.pop_back(); //将最后一个多余的\n给删掉
return resultStr;
}
使用:
std::string str = "Dreams are one of those things that make you happy and going on !";
CCLabelTTF* m_label = CCLabelTTF::create(myWrap(str, 20).c_str(), "Arial", 24);
m_label->setHorizontalAlignment(kCCTextAlignmentLeft);
m_label->setVerticalAlignment(kCCVerticalTextAlignmentTop);
m_label->setPosition(ccp(visibleSize.width/2, visibleSize.height/2));
this->addChild(m_label);
效果:
注释:对于 CCLabelTTF 对齐的设置
m_label->setHorizontalAlignment(kCCTextAlignmentLeft); //设置水平对其
typedef enum
{
kCCTextAlignmentLeft, //左对齐
kCCTextAlignmentCenter, //中心对其
kCCTextAlignmentRight, //右对齐
} CCTextAlignment;
m_label->setVerticalAlignment(kCCVerticalTextAlignmentTop); //设置垂直对其
typedef enum
{
kCCVerticalTextAlignmentTop, //顶端对齐
kCCVerticalTextAlignmentCenter, //中心对其
kCCVerticalTextAlignmentBottom, //底部对齐
} CCVerticalTextAlignment;