CCLabelTTF 如何支持换行符和换行

Posted on 2013-11-19 07:45  Flex/AS Programmer  阅读(1669)  评论(0编辑  收藏  举报

参考自http://www.cocos2d-x.org/wiki/How_does_CCLabelTTF_support_line_breaks_and_wrapping

环境:

cocos2d-x version: cocos2d-2.1rc0-x-2.1.4

函数介绍

我们要讨论的函数是:

static CCLabelTTF * create(const char *string, const char *fontName, float fontSize,const CCSize& dimensions, CCTextAlignment hAlignment);

参数:

const char *string您将在文本中绘制的标签

const char *fontName: 字体名称

float fontSize: 字体大小

const CCSize& dimensions你希望的标签大小

CCTextAlignment hAlignment:标签的文本水平对齐方式

返回值:返回指针类型的CCLabelTTF

标记:另一个使用了不同参数的create().

static CCLabelTTF * create(const char *string, const char *fontName, float fontSize);

如果您使用此函数,参数CCSize& dimensions的值是CCSizeZero,参数CCTextAlignment hAlignment的默认值是kCCTextAlignmentCenter


支持换行符和换行

标签看起来像什么取决于标签内容大小,而内容的大小取决于参数const char stringconst CCSize& dimensions.所以,关键是如何通过参数const char stringconst CCSize& dimensions计算的标签内容大小.
我们这样子处理不同情况:

  • 参数const CCSize& dimensions等于CCSizeZero
    1. 1. 标签内容大小自动计算的。
    2. 2.不换行,完整显示标签,。
    3. 参数const CCSize& dimensions只指定宽度。
    4. 1. 标签宽度等于dimensions.width,标签高度将自动计算。
    5. 2.支持换行,并将完整显示标签。
    6. 参数const CCSize& dimensions指定宽度和高度。
    7. 1. 标签内容大小等于参数CCSize& dimension.
    8. 2. 如果标签不能完全显示在指定的大小内,标签将截断不可见区域。


例子

CCLabelTTF *ttf=CCLabelTTF::create("This is a sentence longer than a line width.\nCocos2d-x", "Thonburi", 20, CCSizeMake(0, 0), kCCTextAlignmentCenter);


CCLabelTTF *ttf=CCLabelTTF::create("This is a sentence longer than a line width.\nCocos2d-x", "Thonburi", 20, CCSizeMake(200, 0), kCCTextAlignmentCenter);

CCLabelTTF *ttf=CCLabelTTF::create("This is a sentence longer than a line width.\nCocos2d-x", "Thonburi", 20, CCSizeMake(200, 43), kCCTextAlignmentCenter);


Copyright © 2024 Flex/AS Programmer
Powered by .NET 8.0 on Kubernetes