libgdx - how to get a Label with wrapped text

2019-01-25 08:14发布

I tried the following code:

Label label = new Label(reallyLongString, skin);
label.setWrap(true);
label.setWidth(100); // or even as low as 10
table.add(label);
...

and yet all I get is a very wide line that draws off the screen.

3条回答
Deceive 欺骗
2楼-- · 2019-01-25 09:02

I've found that this code can solve the issue without any table or wrapping container (for libgdx-1.9.6)

    label = new Label("Some label", skin);
    label.setPosition(600, 50);
    label.setWidth(200);
    label.setHeight(50);
    label.setWrap(true);
    stage.addActor(label);
查看更多
老娘就宠你
3楼-- · 2019-01-25 09:04

If you just want to specify the preferred size for a single widget, wrap it with a Container.

https://github.com/libgdx/libgdx/wiki/Scene2d.ui#layout-widgets

https://libgdx.badlogicgames.com/nightlies/docs/api/com/badlogic/gdx/scenes/scene2d/ui/Container.html

Something like:

Container<Label> labelContainer = new Container(myLabel);
labelContainer.prefWidth(200.0f);

Keep in mind that the actual size will vary depending on the container hierarchy - for example, the labelContainer above will display differently if placed in another layout object.

The size will also vary depending on the viewport, etc.

查看更多
迷人小祖宗
4楼-- · 2019-01-25 09:09

This is the same issue as seen in "How to get a Label to the right size" or "Slider always has default width".

You need to put that label into a table and add the right size to the cell of the table where the label is.

UI widgets do not set their own size and position. Instead, the parent widget sets the size and position of each child. Widgets provide a minimum, preferred, and maximum size that the parent can use as hints. Some parent widgets, such as Table, can be given constraints on how to size and position the children. To give a widget a specific size in a layout, the widget's minimum, preferred, and maximum size are left alone and size constraints are set in the parent.

Source: From the libgdx wiki Scene2D

The solution:

Label label = new Label(reallyLongString, skin);
label.setWrap(true);
label.setWidth(100); // or even as low as 10
table.add(label).width(10f);// <--- here you define the width
查看更多
登录 后发表回答