Libgdx | Scene2d | 设置表格的背景颜色?

10

我正在创建一个菜单(就像flappy bird游戏中死亡后弹出的那个),我创建了一个继承自表格(table)的类,并希望将表格的背景设置为白色。有办法可以做到这一点吗?


1
你应该在你的纹理图集中保留一个纯白色的纹理区域,以便创建纯色的TextureRegionDrawables。将一个白色的TextureRegionDrawable设置为你的表格背景。 - Tenfour04
4个回答

10
你可以像这样做:

你可以这样做:

Pixmap bgPixmap = new Pixmap(1,1, Pixmap.Format.RGB565);
bgPixmap.setColor(Color.RED);
bgPixmap.fill();
textureRegionDrawableBg = new TextureRegionDrawable(new TextureRegion(new Texture(bgPixmap)));
Table table = new Table();
table.setBackground(textureRegionDrawableBg);

记得对纹理和像素图调用dispose()。


7
我看到问题已经解决了,但是其他人要求看代码,而我现在无法评论。
以下是实现类似解决方案的代码,唯一的区别是会提供一个可实例化的类(以便稍后轻松更改表格背景颜色):

https://www.snip2code.com/Snippet/2615417

BackgroundColor backgroundColor = new BackgroundColor("white_color_texture.png");
backgroundColor.setColor(2, 179, 228, 255); // r, g, b, a
table.setBackground(backgroundColor);

因此,通过将白色PNG文件的文件名(如@Tenfour04在上面的评论中提到的)传递给任意BackgroundColor类的构造函数,创建一个BackgroundColor类的实例。

如果您不熟悉后半部分,请参见下面链接的存储库,其中可以找到此类PNG文件的示例。

现在使用实例的setColor(red,green,blue,alpha)方法,然后将实例传递给libGDX表格,使用setBackground(Drawable drawable)方法设置背景。

这并不是为所有人提供的完美解决方案-根据需要进行修改。

备份:

https://github.com/ronrihoo/libGDX-Table-Background-Color


2
使用setBackground(Drawable drawable)方法解决了表格的问题。我创建了一个匿名类的drawable,其中包含一个在匿名类的draw方法中呈现的sprite。请注意保留HTML标签。

1
快点,你必须放置解决方案。 - Humberd

0

对于那些要求提供示例代码的人,这里有一个简单的实现。(我刚刚发现了BaseDrawable,它在这种情况下非常好用!)


 public static class ColorDrawable extends BaseDrawable {
    private float r, g, b, a;
    private Color savedBatchColor = new Color();

    public ColorDrawable(float r, float g, float b, float a) {
        this.r = r;
        this.g = g;
        this.b = b;
        this.a = a;
    }
    @Override
    public void draw(Batch batch, float x, float y, float width, float height) {
        // Save the batch colour as we are about to change it
        savedBatchColor.set(batch.getColor());
        batch.setColor(r, g, b, a);
        // Draw a white texture with the current batch colour
        batch.draw(Assets.blankWhite, x, y, width, height);
        batch.setColor(savedBatchColor);
    }
}

使用方法如下:


    // Load a texture region from a texture atlas with a white image
    Assets.blankWhite = myTextureAtlas.findRegion("some_white_image");

    . . .

    // Create a new background drawable with the colour provided
    ColorDrawable background = new ColorDrawable(0.7f, 0.9f, 0.9f, 1f);
    table.setBackground(background);

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