我正在创建一个菜单(就像flappy bird游戏中死亡后弹出的那个),我创建了一个继承自表格(table)的类,并希望将表格的背景设置为白色。有办法可以做到这一点吗?
你可以这样做:
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()。
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)方法设置背景。
这并不是为所有人提供的完美解决方案-根据需要进行修改。
备份:
对于那些要求提供示例代码的人,这里有一个简单的实现。(我刚刚发现了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);