您的位置:首页 > 移动开发 > Cocos引擎

cocos2dx显示CCLabelTTF的指定宽度

2015-10-20 19:42 429 查看
好久不写文章了,现在我用的还是cocos2dx2.2.2版本进行开发,所以一些小功能还是写出来了

如果一个CCLabelTTF的长度太长了,但是全部显示出来,可能效果不好看,所以这里就根据固定长度显示,超过的自动抹去。

方法如下:

void setNameLength(std::string nameStr)
{

int charNum =
0;
    int lMax =
0;
    CCLabelTTF * nameTTF =
CCLabelTTF::create(nameStr.c_str(),
"Arial", 20);
    float strLength = nameTTF->getContentSize().width;
    if (strLength > 100) {
        charNum =
NAME_DOWN_MAX;
        lMax = (180<strLength)?180:strLength;
    }
    else
    {
        lMax = strLength;
    }
    printf("lMax is %d\n", lMax);

    std::string  string1 = nameStr;
    std::string  string2;
    if (strLength>lMax)
    {
       
const char * s = nameStr.c_str();
       
int i = 0, j =
0;
        while (s[i])

        {
            if ((s[i] &
0xc0) != 0x80)
            {
               
j++;
               
if (j>1) {
                   
std::string  string3 = string1.substr(0,i).c_str();
                   
nameTTF = CCLabelTTF::create(string3.c_str(),
"Arial", 22);
                   
strLength = nameTTF->getContentSize().width;

                    
if ((strLength)>lMax) {
                       
break;
                   
}
                   
else
                   
{
                       
string2 = string1.substr(0,i).c_str();
                   
}
                }
            }
            i++;
        }
    }
    else
    {
        string2 = nameStr;
    }
CCLabelTTF* pLabelTTF = CCLabelTTF::create(string2.c_str(), "Arial", 32);
pLabelTTF->setPosition(ccp(240, 160));
this->addChild(pLabelTTF);//这个pLabelTTF就是显示固定宽度的区域
}

当然这个功能也可以用遮罩实现,也比较简单
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: