Outdated Docs > How does CCLabelTTF support line breaks and wrapping

How does CCLabelTTF support line breaks and wrapping

Environment

  • cocos2d-x version: cocos2d-0.99.5-x-0.8.0.

Function Introduction

The function we will discussed is:

CCLabelTTF * CCLabelTTF::labelWithString(const char *label, CGSize dimensions, UITextAlignment alignment, const char *fontName, float fontSize);
  • parameters #const char label: The text you will draw in the label; #CGSize dimensions**: The size of label you expected; # **UITextAlignment alignment: The text alignment in the label; #const char fontName: Font name; #float fontSize**: Font Size; ** return value: return the pointer of CCLabelTTF.
  • remark:
    There is another function named labelWithString with different parameters.

    CCLabelTTF * CCLabelTTF::labelWithString(const char *label, const char *fontName, float fontSize);

If you use this function,it’s means that the value of paramater CGSize dimensions is CGSizeZero,and the value of parameter UITextAlignment alignment is UITextAlignmentCenter.

Support Line Breaks and Wrapping

What is the label looks like depend on the content size of the label,and the content size is depend on the parameter const charlabel* and CGSize dimensions.
So the key is how to calculate the content size of label by parameters const charlabel* and CGSize dimensions.
We treat different cases like this:

  • parameter CGSize dimensions equal with CGSizeZero **# The label content size is auto-calculated. **# The label will be full displayed.No line wrap.
  • parameter CGSize dimensions only specified the width. # The label width will equal withdimensions.width**,and the label height will be auto-calculated. **# The line wrap will happen.And the label will be full displayed.
  • parameter CGSize dimensions specified the width and height. # The label content size will equal with parameterCGSize dimensions**. **# The label will be cut off if it’s can’t be full displayed in the specified size.

Samples

Now,let’s have a look at the list which show you the logic visually.
|*. sample code|*. result picture|
| CCLabelTTF::labelWithString(
“This is a sentence longer than a line width.2d-x”,
CGSizeMake(**0, 0**), UITextAlignmentCenter, “Thonburi”, 20)| |
| CCLabelTTF::labelWithString(
“This is a sentence longer than a line width.2d-x”,
CGSizeMake(**200, 0**), UITextAlignmentCenter, “Thonburi”, 20)| |
| CCLabelTTF::labelWithString(
“This is a sentence longer than a line width.2d-x”,
CGSizeMake(**200, 75**), UITextAlignmentCenter, “Thonburi”, 20) | |

full.jpg (18.1 kB) zhangbin@cocos2d-x.org, 2011-03-06 20:35

cut.jpg (16.7 kB) zhangbin@cocos2d-x.org, 2011-03-06 22:05

wrap.jpg (17.2 kB) zhangbin@cocos2d-x.org, 2011-03-06 22:07

Sign up for our newsletter to keep up with the latest developments, releases and updates for Cocos2d-x.