Label::setString() strips white spaces at the end. I require it not to, what can I do?

I need to know the metrics of a label in advance and then clear its text to add it char by char at a latter time. This is used to achieve the effect of the attached video.

I have successfully implemented the same for other libraries and game engines. As long as there is a label or text field ui component that auto resizes to enclose all its text content it can be done.

My problem in porting this solution to cocos2d is that Label seems to strip white spaces at the end. When I set the full text and then try to use getContentSize() to measure the space requirements of that text, the result doesn’t include the last white space.

This is how I’m calculating the size of a white space, for a particular font, as a temporal fix:

float space_width = cocos2d::RefPtr<cocos2d::Label>(Label::createWithTTF("A A", fontName, fontSize))->getContentSize().width - cocos2d::RefPtr<cocos2d::Label>(Label::createWithTTF("AA", fontName, fontSize))->getContentSize().width;

Is there a call to make Label stop stripping the last white space?

https://discuss.cocos2d-x.org/uploads/default/original/3X/f/4/f431dc33eb303f1049beecf9a242ec46429e87e7.mov

Which version of cocos2d-x are you using at the moment?

Something was changed in the v3.17 release, which broke the way Label and UIRichText elements worked by trimming off the white space at the end of the line, even if the line wasn’t being split into multiple lines.

I’ve checked in a fix for it, so if you want to test it out, just merge the changes in with your version and please let me know if it works for you.

Here is the issue:

Here is the fix:

Specifically these changes:

My version is 3.17. Merging. I will post again to let you know after I build and test again, but judging for what that code does, It will probably work.

Update: Confirming. After merging the changes, white spaces at the end aren’t removed any more. I deleted my temporal fix as now it causes double spacing between labels in my game.

I’m glad it’s working, and hopefully it will be approved and merged in before the next release.

1 Like

If it gets rejected I will have to calculate spaces again to manually apply to labels position when there are many labels in the same line. So I hope it is not. The problem with doing it that way is that I’m thinking in allowing different fonts in the same line in my game’s dialog box, calculating the spaces for each loaded font would probably impose some overhead.

It seems that UIRichText.h can be reverted back to original from 3.17 release.

@drelaptop what do you think of the PR above?

It’s a good patch, and I have replied at that PR.

That file, yes, reverted back to the original in the 3.17 release, but UIRichText.cpp still required the removal of a section of code that was forcing the trimming of trailing spaces. Here is the commit with the change: