【问题标题】:Get the size of wrapped text in Label获取 Label 中换行文本的大小
【发布时间】:2015-07-08 18:34:20
【问题描述】:

如果我使用自动换行在 500x500 区域中创建标签,我如何找出换行文本的高度?我正在寻找黄色高度,而不是鲑鱼高度。

【问题讨论】:

    标签: cocos2d-x-3.0


    【解决方案1】:

    @idrise 的答案不适用于系统字体这里我给出一个更灵活的答案

    假设我们要创建一个固定宽度的文本/标签,但根据文本的长度动态高度。为此,您可以使用以下代码:

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

    显然对于固定高度,您也可以这样做。

    希望帮助某人:]

    【讨论】:

    • 谢谢哥们。我正在寻找类似于 setDimensions for RichText 但找不到的东西。 cocos2d-x的api我一般都喜欢,但是现在感觉RichText好像是cocos2d-x中最差的api了。最终,老牌老牌帮了大忙。
    【解决方案2】:

    这似乎有点违反直觉。 首先,您将尺寸设置为高度过大。 调用 getLineHeight 和 getStringNumLines 将根据传递的宽度计算高度。 您将宽度和高度发送回 setDimensions。 现在您的标签 getContentSize() 将返回文本的实际大小。

    IE

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

    【讨论】:

    • 当使用Label::createWithSystemFont(..) 时,此答案在getLineHeight() 中给出Not supported system font 断言。对于这种情况,请检查我的答案。
    【解决方案3】:

    他们添加了您想要的功能:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多