为什么具有多边形的 actor 在 libgdx 中不能正常填充?

Why actors with polygons do not filled normally in libgdx?

所以这里有两个例子,我在 table 中有两张图片,但大小不同。一个使用纹理和另一个使用多边形的示例之间的唯一区别。

  1. 纹理 x.png 为 130x130,y.png 为 75x75

    Image image1 = new Image(new TextureRegionDrawable(new TextureRegion(new Texture("y.png"))));
    Image image2 = new Image(new TextureRegionDrawable(new TextureRegion(new Texture("x.png"))));
    mainTable.setFillParent(true);
    mainTable.row();
    mainTable.add(image1).uniform().fill();
    mainTable.add(image2).uniform();
    mainTable.pack();
    

输出:

如您所见,第一张图片已填充为第二张图片的尺寸,但在基础图片中它们的尺寸不同。


  1. 多边形

    Image image1 = new Image(new PolygonRegionDrawable(new PolygonRegion(getSolidTexture(Color.YELLOW), new float[]{0, 0, 75, 75, 0, 75, 75, 0}, new short[]{0, 1, 2, 0, 3, 2})));
    Image image2 = new Image(new PolygonRegionDrawable(new PolygonRegion(getSolidTexture(Color.YELLOW), new float[]{0, 0, 130, 130, 0, 130, 130, 0}, new short[]{0, 1, 2, 0, 3, 2})));
    mainTable.setFillParent(true);
    mainTable.row();
    mainTable.add(image1).uniform().fill();
    mainTable.add(image2).uniform();
    mainTable.pack();
    

哪里

    public TextureRegion getSolidTexture(Color color) {
        Pixmap p = new Pixmap(1, 1, RGBA8888);
        p.setColor(color);
        p.fill();
        Texture t = new Texture(p);
        return new TextureRegion(t);
    }

输出:

如您所见,第一张图片没有填充到第二张图片的大小。

实际上,为什么多边形的行为不同?

正如我发现的,PolygonRegion 必须与顶点大小相同,并且只有在那之后它才能正常缩放。

在我的代码中,我只需要将我的顶点数组缩放到与我的像素图相同的大小。

    float[] vertices1 = {0, 0, 75, 75, 0, 75, 75, 0};
    vertices1 = GeometryUtils.scale(vertices1, 0, 0, 1, 1);
    Image image1 = new Image(new PolygonRegionDrawable(new PolygonRegion(resources.getSolidTexture(Color.YELLOW), vertices1, new short[]{0, 1, 2, 0, 3, 2})));
    float[] vertices2 = {0, 0, 130, 130, 0, 130, 130, 0};
    vertices2 = GeometryUtils.scale(vertices2, 0, 0, 1, 1);
    Image image2 = new Image(new PolygonRegionDrawable(new PolygonRegion(resources.getSolidTexture(Color.YELLOW), vertices2, new short[]{0, 1, 2, 0, 3, 2})));
    mainTable.setFillParent(true);
    mainTable.row();
    mainTable.add(image1).uniform().fill();
    mainTable.add(image2).uniform();
    mainTable.pack();

至少对我来说,我在 Google 或互联网上根本找不到该信息是非常奇怪的。绝望之后,我在调试时找到了解决方案。