Text Wrapping in Cocos2d-x
Asked Answered
R

1

5

I am trying to get my text labels to automatically resize if the text is longer than the box they are in. I also want it to support multi-line functionality. I have done some searching online and saw that it used to work something like this:

CCLabelTTF::labelWithString(“This is a sentence longer than a line width.2d-x”, CGSizeMake(**0, 0**), UITextAlignmentCenter, “Thonburi”, 20);

but that seems to no longer be available in cocos so I am not sure what to do.. Right now I have my label set up as follows:

myQuestion = Label::createWithTTF("Testing to see if text wrap will work" ,c_strFontNameBase, 50);
myQuestion->setPosition(boxLabel->getContentSize().width/2, boxLabel->getContentSize().height/2);
boxLabel->addChild(myQuestion, 50);

Is there some way I can use a similar way to the top example to make mine work? This doesn't seem like it should be very hard thing to do but I am finding a lack of documentation on it online...

Raze answered 11/3, 2015 at 17:1 Comment(0)
O
8

I believe, you can only make one dimension of the label auto-resizable i.e. either width or height can be auto-resizable. By default when you create label as follows, width of the labels are set to resize automatically with fixed height:

auto label = Label::createWithTTF("Hello World gsdhsgdh gshdghsg yutywe gdgshdgy bnbjh hshhashgy hjnbdnsdhh ghhsgdhg ghghghsd ghhghsd ghghghgsd jkjkhsdjkj ououisdusydsi kkjkxncmxcjh kcxhjxhcjx jkuiushjxchxjch hjhjchxuyuychjc ", "fonts/Marker Felt.ttf", 24);
// position the label on the center of the screen
label->setPosition(Vec2(origin.x + visibleSize.width/2,
                            origin.y + visibleSize.height - label->getContentSize().height));

// add the label as a child to this layer
this->addChild(label, 1);

But if you want multi-line support i.e. fixed width and resizable height you just need to set dimension of the label with fixed width and zero height as:

label->setDimensions(300, 0);

I hope it will help.

Oratory answered 11/3, 2015 at 19:22 Comment(2)
Note that the way to do this with BMFonts work the same way static_cast<Label*>(my_ui_TextBMFont_widget->getVirtualRenderer())->setDimensions(375, 0);Disclose
If using cocos2d::Text instead of label use the same strategy as above but use setTextAreaSize instead of setContentSizeSaliva

© 2022 - 2024 — McMap. All rights reserved.