2
\$\begingroup\$

I'm trying to change the texture of an Image actor on my Scene2D stage, however I can't seem to get it working. It seems like setDrawable() doesn't really do anything.

For example, this will make the texture of the Image cookie.png:

Image itemImage = new Image(new TextureRegionDrawable(new TextureRegion(new Texture(Gdx.files.internal("cookie.png")))));
itemImage.setPosition(10, 10);
getStage().addActor(itemImage);

However, this will not:

Image itemImage = new Image();
itemImage.setPosition(10, 10);
itemImage.setDrawable(new TextureRegionDrawable(new TextureRegion(new Texture(Gdx.files.internal("cookie.png")))));
getStage().addActor(itemImage);

Am I missing something?

\$\endgroup\$
4
\$\begingroup\$

In the second case it is not drawing because the constructor with no arguments doesn't set a width and height for the image, however the constructor that takes the drawable obtains the values from it.

To fix in your case:

Texture texture = new Texture(Gdx.files.internal("cookie.png"));
Image itemImage = new Image();
itemImage.setPosition(10, 10);
itemImage.setDrawable(new TextureRegionDrawable(new TextureRegion(texture)));
itemImage.setSize(texture.getWidth(), texture.getHeight());
getStage().addActor(itemImage);

Also I'd save the textures as a field to later dispose of them (or you could obtain the drawable from the Image parse it to Texture and dispose it).

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.