Libgdx Scene2d - 如何设置演员(TextField)的填充?

6

我一直在尝试为一个演员设置填充或类似的内容,但无法弄清楚正确的方法。我猜想可能需要在皮肤中添加一些东西?

我有这个文本字段:

        textboxskin = new Skin();
        textboxskin.add("textfieldback", new Texture("data/textfieldback.png"));
        textboxskin.add("cursor", new Texture("data/cursortextfield.png"));
        textboxskin.add("selection", new Texture("data/selection.png"));
        textboxskin.add("font", font);

        TextFieldStyle textfieldstyle = new TextFieldStyle();
        textfieldstyle.background= textboxskin.getDrawable("textfieldback");
        textfieldstyle.disabledFontColor=Color.BLACK;
        textfieldstyle.font=textboxskin.getFont("font");
        textfieldstyle.fontColor=Color.WHITE;
        textfieldstyle.cursor=textboxskin.getDrawable("cursor");
        textfieldstyle.selection=textboxskin.getDrawable("selection");  


        textfieldusername = new TextField("username", textfieldstyle);

这看起来像这样:

输入图片描述

正如你所看到的,它看起来左对齐很糟糕...

3个回答

12

编辑: 我尝试做以下操作,并且在我的测试中它起作用:

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

在搜索libgdx API时,我没有找到一种指定TextField组件内文本填充的方法。

作为解决方法,您可以复制原始的TextField源代码并创建一个新的TextField,使用另一个名称提供实现填充的方式。

复制libgdx TextField的内容(https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/TextField.java?source=cc)到另一个文件中,并将其称为MyTextField(例如)。用新类名替换损坏的TextField引用。

创建一个名为paddingLeft的新变量,例如:

public float paddingLeft = 0.0f;

在draw()方法中,您可以将填充值添加到总和中,以定义字符串的新位置。代码中所说的是:
font.draw(batch, displayText, x + bgLeftWidth + textOffset, y + textY + yOffset, visibleTextStart, visibleTextEnd);

替换为:

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

(注意第二段代码中的“+ leftPadding”)
接下来,如果您正在使用皮肤,请记得在uiskin.json文件中引用您的TextField。
mypackage.MyTextField$TextFieldStyle: {
    default: { selection: selection, background: textfield, font: default-font, fontColor: white, cursor: cursor }
}

并在您的代码中使用它:

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

这不是理想的方式,但可以工作。


2
使用Table类来布置scene2d UI。设置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();

在主循环中调用以下内容:
stage.act(Gdx.graphics.getDeltaTime());
stage.draw();

更多关于表格的信息,请参见:http://code.google.com/p/table-layout/


1
你可以使用NinePatch。它将纹理分成九个“补丁”,你定义它们的高度和宽度,然后将其提供给NinePatchDrawable,你可以将其提供给TextButton。我相信外部的“补丁”充当边距,在一些微调后(不费力),它看起来很棒并且可以实现你的目标。
我从这篇文章中了解到它们: 将九宫格图像作为Libgdx Scene2d按钮背景加载看起来很糟糕

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接