Get the size of the wrapped text in a label

If I create a 500x500 area shortcut with wordwrap, how can I find out the height of the wrapped text? I am looking for yellow height, not salmon height.

enter image description here

+3


source to share


3 answers


@Idrise's answer does not work for system font. And here I am giving a more flexible answer .

Suppose we want to create a text / label that has a fixed width but dynamic height according to the length of the text. for this you can use the code below:

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 length
////
auto dynamicHeight = title->getContentSize().height; // According to text length :)

      



And obviously for a fixed height, you can do the same.

Hope Help someone:]

+4


source


This might sound a little counterintuitive. First, you are dimensioning too high. Calling getLineHeight and getStringNumLines will calculate the height based on the passed width. You are sending width and height back to setDimensions. Now your getContentSize () labels will return the actual text size.

IE



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

      

0


source


They added the functionality we needed:

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 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);

      

0


source







All Articles