Libgdx, how to draw a tinted image on a pixmap

If you have to draw a tinted pixmap over another pixmap (as you would do with SpriteBatch.draw) with Libgdx there are a few solutions:

As of now I was using the C solution and recompiling Libgdx for mac/linux/windows/android, but now that I have to work on iOs I decided to just use some custom Java function. So here it is:

    public static void drawImageTint(final Pixmap destination, final Pixmap source, final int dx, final int dy, final int sx, final int sy, final int width, final int height,
            final com.badlogic.gdx.graphics.Color c)
    {
        if (c != null && (c.r < 1f || c.g < 1f || c.b < 1f))
        {
            for (int x = 0; x < width; x++)
            {
                for (int y = 0; y < height; y++)
                {
                    int sourceColorInt = source.getPixel(x + sx, y + sy);
                    int currentColorInt = destination.getPixel(x + dx, y + dy);

                    final int rd = 0xFF & (currentColorInt >> 24);
                    final int gd = 0xFF & (currentColorInt >> 16);
                    final int bd = 0xFF & (currentColorInt >> 8);

                    int r = 0xFF & (sourceColorInt >> 24);
                    int g = 0xFF & (sourceColorInt >> 16);
                    int b = 0xFF & (sourceColorInt >> 8);
                    int a = 0xFF & (sourceColorInt >> 0);

                    r = (int) (r * c.r);
                    g = (int) (g * c.g);
                    b = (int) (b * c.b);
                    r = Math.max(Math.min(r, 255), 0);
                    g = Math.max(Math.min(g, 255), 0);
                    b = Math.max(Math.min(b, 255), 0);

                    r = (int) (r * c.a + rd * (1 - c.a));
                    g = (int) (g * c.a + gd * (1 - c.a));
                    b = (int) (b * c.a + bd * (1 - c.a));

                    destination.setColor(((r << 24) + (g << 16) + (b << 8) + (a << 0)));
                    destination.drawPixel(x + dx, y + dy);
                }
            }
        }
        else
        {
            destination.drawPixmap(source, dx, dy, sx, sy, width, height);
        }
    }

This won’t blend alpha, it will just overwrite source image alpha to the destination, but this can be changed easily

(Just in case, this code snippet is CC0, you can do whatever you want with it, attribution is not needed)

Comments are closed.