cocos2dx显示CCLabelTTF的指定宽度

来源:互联网 发布:爱淘宝的红包怎么领取 编辑:程序博客网 时间:2024/04/28 20:44

好久不写文章了,现在我用的还是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就是显示固定宽度的区域

}


当然这个功能也可以用遮罩实现,也比较简单


0 0
原创粉丝点击