Libgdx Scene2d - Set actor ( TextField ) padding?

烈酒焚心 提交于 2019-12-05 09:38:01

Use the Table class to lay out scene2d UIs. To set up the Table:

stage = new Stage();
Table table = new Table();
table.setFillParent(true);
stage.addActor(table);
table.add(textFieldUsername).padBottom(20f); //also use padTop, padLeft, and padRight
table.row();

In the main loop, call:

stage.act(Gdx.graphics.getDeltaTime());
stage.draw();

For more information on tables, see: http://code.google.com/p/table-layout/

EDIT: I tried to do the following and it worked in my tests:

textfieldstyle.background.setLeftWidth(textfieldstyle.background.getLeftWidth() + 10);

Searching the libgdx API I couldn't find a way to specify padding for the text inside the TextField component.

As a workaround, yout could copy the original TextField source and create a new TextField, with another name providing a way to implement the padding.

Copy the contents of the libgdx TextField (https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/TextField.java?source=cc) to another file and call it MyTextField (as an example). Replace the broken TextField references with the new class name.

Create a new variable called paddingLeft, for example:

public float paddingLeft = 0.0f;

In the draw() method, you can add your padding to the sum to define a new position for the String. Where the code says:

font.draw(batch, displayText, x + bgLeftWidth + textOffset, y + textY + yOffset, visibleTextStart, visibleTextEnd);

replace with:

font.draw(batch, displayText, x + bgLeftWidth + textOffset + leftPadding, y + textY + yOffset, visibleTextStart, visibleTextEnd);

(notice the " + leftPadding" in the second code)

Then, if you are using skins, remember to reference your TextField in the uiskin.json file:

mypackage.MyTextField$TextFieldStyle: {
    default: { selection: selection, background: textfield, font: default-font, fontColor: white, cursor: cursor }
}

and use it in your code:

MyTextField txtTest = new MyTextField("Test", skin);
txtTest.leftPadding = 10.0f;

This is not the ideal way, but will work.

HappyPandaFace

You could use a NinePatch. This separates your texture into nine "patches" you define their height and width, and then you give it to a NinePatchDrawable which you can give to a TextButton. I believe the outer "patches" act as margins and with some tweaking (not strenuous) it would look great and accomplish your goals.

I learned about them from this post: Loading nine-patch image as a Libgdx Scene2d Button background looks awful

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!