获取Label中包装文本的大小

时间:2015-04-29 12:52:40

标签: cocos2d-x-3.0

如果我使用wordwrap在500x500区域创建标签,我如何找出包装文本的高度?我正在寻找黄色的高度,而不是鲑鱼的高度。

enter image description here

3 个答案:

答案 0 :(得分:4)

@idrise的答案不适用于系统字体在这里我给出了一个更灵活的答案

假设我们要创建一个固定宽度的文本/标签,但根据文本的长度创建动态高度。为此你可以使用下面的代码:

Label *lbl = Label::createWithSystemFont("aaa aaa aaa aaa aaa aaa", "Arial", 50);
lbl->setDimensions(FIXED_WIDTH, 0); // "0" means we don't care about wrapping vertically, hence `getContentSize().height` give a dynamic height according to text's length
////
auto dynamicHeight = title->getContentSize().height; // According to text's length :)

显然,对于固定高度,你可以做同样的事情。

希望帮助某人:]

答案 1 :(得分:0)

这似乎有点反直觉。 首先,您将尺寸设置为过大的高度。 调用getLineHeight和getStringNumLines将根据传递的宽度计算高度。 您将宽度和高度发送回setDimensions。 现在你的标签getContentSize()将返回文本的实际大小。

IE

        label->setDimensions(width, 2000);
        label->setDimensions(width,label->getStringNumLines() * 
ceil(label->getLineHeight()));

答案 2 :(得分:0)

他们添加了您想要的功能:

Added three overflow type to new label: CLAMP, SHRINK, RESIZE_HEIGHT.

Overflow type is used to control label overflow result, In SHRINK mode, the font size will change dynamically to adapt the content size. In CLAMP mode, when label content goes out of the bounding box, it will be clipped, In RESIZE_HEIGHT mode, you can only change the width of label and the height is changed automatically. For example:

//Change the label's Overflow type
label->setOverflow(Label::Overflow::RESIZE_HEIGHT);

    mTexto=Label::createWithTTF(mTextoHelp.c_str(),CCGetFont(), 30);
    mTexto->setHeight(100.f);
    mTexto->setOverflow(Label::Overflow::RESIZE_HEIGHT);
    mTexto->setDimensions(mSize.width*0.8f, 0.f);