加载九个补丁图像作为Libgdx Scene2d按钮背景看起来很糟糕

P.T*_*.T. 4 java nine-patch libgdx

我正在尝试使用Nine Patch作为Libgdx Scene2d UI按钮的背景.这是装载,但它真的很难看.我可以看到"元数据"像素,它被拉伸就好像它只是一个普通的图像(按钮上的文字是"继续"):

九个补丁按钮的丑陋形象

我正在通过(libgdx)将.9.png文件直接加载到NinePatchDrawable(libgdx)中,NinePatch如下所示:

this.dialogButtonUp = new NinePatchDrawable(
   new NinePatch(new Texture(Gdx.files.internal("data/button-round.9.png"))));
this.dialogButtonDown  = new NinePatchDrawable(
   new NinePatch(new Texture(Gdx.files.internal("data/button-round-down.9.png"))));
Run Code Online (Sandbox Code Playgroud)

然后我创建一个TextButtonStyle描述按钮,并引用两个NinePatchdrawable:

TextButton.TextButtonStyle buttonStyle = new TextButton.TextButtonStyle();
buttonStyle.font =  aValidFontReally;
buttonStyle.fontColor = Color.BLACK;
buttonStyle.up = this.dialogButtonUp;
buttonStyle.down = this.dialogButtonDown;
buttonStyle.pressedOffsetX = -2;
Run Code Online (Sandbox Code Playgroud)

我通过一个Dialog盒子间接构建按钮:

new Dialog( ... ).button("Continue", null, buttonStyle);
Run Code Online (Sandbox Code Playgroud)

我检查了.9.png文件以确保:

  • 资产文件在Eclipse中刷新
  • 元数据边界像素要么是完全不可见的,要么是完全可见的黑色
  • Android draw9patch工具可以加载图像并验证它们

关于检查或更改内容的任何其他建议?

P.T*_*.T. 10

感谢来自@RodHyde的一些指针,看起来libgdx NinePatch类被设计为接受"后处理"的九个补丁纹理(即,使用单独的整数值来描述如何将单个纹理切割成补丁).这种"处理"通常是将".9.png"文件打包成一个副作用TextureAtlas(参见https://github.com/libgdx/libgdx/wiki/Texture-packer#ninePatches).纹理图集是一个非常好的主意(特别是当你的UI包含一堆不同的纹理元素时),所以这是有道理的,但在开发和尝试运行时有点令人惊讶.

为了解决这个问题,我可以直接包含我写的".9.png"文件:

private static NinePatch processNinePatchFile(String fname) {
    final Texture t = new Texture(Gdx.files.internal(fname));
    final int width = t.getWidth() - 2;
    final int height = t.getHeight() - 2;
    return new NinePatch(new TextureRegion(t, 1, 1, width, height), 3, 3, 3, 3);
}
Run Code Online (Sandbox Code Playgroud)

这会加载纹理,创建一个修剪掉1像素元数据边框的子区域,然后猜测九个补丁边框元素是3像素宽/高.(通过在纹理数据中进行正确计算似乎是可能的,但不值得付出努力 - 在这种情况下只需将纹理放在图册中.)

  • NinePatch javadoc得到了改进,使其更加清晰:https://github.com/libgdx/libgdx/commit/5ce8dc04153234c760b3753fe3a6b4e6fe1653ea#gdx/src/com/badlogic/gdx/graphics/g2d/NinePatch.java (2认同)