Search code examples
androidimagelibgdxdrawabletexture-atlas

How can I set an image in libgdx with a textureregion


I have just started to use TexturePacker, TextureAtlas and TextureRegions in my app.

I currently have a class called card, that extends Image, and I want to be able to set the graphic on a card as something from my atlas.

I can do this fine when I create the card as one of the many constructors for Image is Image(TextureRegion textureRegion).

However, my card will need to change graphic during my game, and I need to be able to set this also from the atlas.

I can currently only find a way of changing the Image by setting the Drawable on it.

Is this the only way, seeing as there is a constructor to set the graphic using a TextureRegion, I find it odd that I can't do the same with a setter method?

If not, how should I go about this? Can I convert a TextureRegion into a Drawable? Should I cache this somewhere to save processing the TextureRegion into a Drawable each time? I am using an AssetManager to give me the TextureAtlas, so I presume there is only one instance of the TextureAtlas, but that won't hold true if I keep having to convert the TextureRegion into a Drawable will it? I'll have to cache this myself won't I?


Solution

  • There is simple way to convert TextureRegion to Drawable (which is btw interface) by creating TextureRegionDrawable object:

        TextureRegion region = ...
    
        drawable = new TextureRegionDrawable(region);
    

    More reasonable for me seems to be just creating two Images and switch between them using

        image.setVisible(isVisible);
    

    If you need to change textures one to another all the time you hould consider using Animation object to achieve this