libgdx - 图片 setDrawable 不工作

libgdx - Image setDrawable not working

在运行时更改 Actor(图像子类)纹理不起作用。 仅绘制构造函数调用的纹理参数。我搜索了 一个解决方案,但没有任何效果。最后一次尝试是在 图像构造函数,最终只是设置 Drawable 然后调用 setSize().

CircuitElement 扩展图像

public class Bulb extends CircuitElement {
    boolean on;
    int x, y;

    TextureRegion bulbOn;
    TextureRegion bulbOff;

    public Bulb (int x, int y, int id, TextureRegion i) {
        super(i);

        on = false;
        //this.x = x;
        //this.y = y;
        this.id = id;

        TextureAtlas atlas = new TextureAtlas(Gdx.files.internal("switch.pack"));
        bulbOn = atlas.findRegion("bulbOn");
        bulbOff = atlas.findRegion("bulbOff");
        setWidth(bulbOn.getRegionWidth());
        setHeight(bulbOn.getRegionHeight());
        setBounds(0, 0, getWidth(), getHeight());
        debug();

        this.addListener(new ClickListener() {
            public void clicked(InputEvent event, float x, float y) {
                if (on) {
                    on = false;
                } else {
                    on = true;
                }
                System.out.println(on);
            }
        });
    }

    @Override
    public void draw (Batch batch, float parentAlpha) {
        if (on) {
            setDrawable(new SpriteDrawable(new Sprite(bulbOn)));
            //setWidth(bulbOn.getRegionWidth());
            //setHeight(bulbOn.getRegionHeight());
            //setBounds(0, 0, getWidth(), getHeight());
            setSize(getPrefWidth(), getPrefHeight());
        } else {
            setDrawable(new SpriteDrawable(new Sprite(bulbOff)));
            //setWidth(bulbOff.getRegionWidth());
            //setHeight(bulbOff.getRegionHeight());
            //setBounds(0, 0, getWidth(), getHeight());
            setSize(getPrefWidth(), getPrefHeight());
        }
    }
}

我必须在我自己的绘制方法中调用 super.draw(),之后 调用 setDrawable 和 setSize.

尝试在初始化期间将任何 Drawable 作为 Image 的构造函数参数传递。然后您可以在运行时使用 setDrawable() 更改 Drawable。这是 Image class.

中的一些错误
// initialize
Image kidImage = new Image(dummyDrawable);
// instead of Image kidImage = new Image();
..
..
// run time
kidImage.setDrawable(realDrawable);

这绝对有效。