Search code examples
javauser-interfacelibgdxgame-engine

libGDX: Change the color of a PNG according to user's input


i hope you can help me. I have a game where transparent textures are loaded and should be colored according to the user's choice (HEX code) at the beginning of the game.

My game has tiles where the gameFigures will be placed (centered). Tiles are 50x50 are so is my png. it has a transparent background and the vector of my Figure has transparent stuff that should be colored. It looks something like this:

enter image description here

I am using libGDX engine, and i am really frustrated because of this problem. Any help is appreciated!

Thanks alot!


Solution

  • To change colors programmatically in LibGDX you need to use an image (png or jpg) with white pixels you can achieve this effect splitting your image in 2 parts, one for the part that you don't want the color to be changed and one for the parts that you do. Here's an example:

    Example color

    Code:

    public class ExampleGame extends InputAdapter {
    
        SpriteBatch batch;
        Color crownColor;
    
        public ExampleGame() {
            batch = new SpriteBatch();
            crownColor = Color.WHITE;
        }
    
        @Override
        public boolean touchDown(int screenX, int screenY, int pointer, int button) {
            crownColor = Color.RED;
            return false;
        }
    
        public void render(TextureRegion player, TextureRegion crown) {
            batch.begin();
            batch.setColor(Color.WHITE); // Else player will be affected by crownColor too
            batch.draw(player, 0, 0);
            batch.setColor(crownColor);
            batch.draw(crown, 0, 0);
            batch.end();
        }
    }