rzx217
rzx217

Reputation: 13

libgdx - Image setDrawable not working

Changing the Actor(Image subclass) texture at runtime doesn't work. Only the texture argument of the constructor call is drawn. I searched for a solution, but nothing did work. Last try was looking up the code in the Image constructor, which ultimately just sets the Drawable und then calls setSize().

CircuitElement extends Image

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());
        }
    }
}

Upvotes: 1

Views: 530

Answers (2)

Neerkoli
Neerkoli

Reputation: 2695

Try to pass any Drawable as the constructor argument of Image during initialization. Then you can change the Drawable at runtime using setDrawable(). It is some bug in the Image class.

// initialize
Image kidImage = new Image(dummyDrawable);
// instead of Image kidImage = new Image();
..
..
// run time
kidImage.setDrawable(realDrawable);

This will definitely work.

Upvotes: 1

rzx217
rzx217

Reputation: 13

I had to call super.draw() in my own draw-method, after calling setDrawable and setSize.

Upvotes: 0

Related Questions