Search code examples
androidtintcolorfilter

How to fill a B&W PNG icon with a color in Android?


I want to fill PNG icons with colors.

Here is my current code:

            ingredientImageView.setImageResource(context.getResources().getIdentifier("ico_" + ingredient.replace("-", "_"), "drawable", context.getPackageName()));
            ingredientImageView.setColorFilter(iconTextColor,PorterDuff.Mode.SRC_IN);

This code makes my icons like this:

enter image description here

iconTextColor here is black. But color filter fills the white parts of the icon. You can find the icon below:

enter image description here

Black lines should become the color that I want. But inside of the leaves(in that icon) should remain white.

So, transparent -> transparent, white->white, black->dynamicColor

How can I do that?


Solution

  • You can try to define a custom ColorMatrix with random r g b values:

        Random rand = new Random();
        int r = rand.nextInt(256);
        int g = rand.nextInt(256);
        int b = rand.nextInt(256);
    
        ColorMatrix cm = new ColorMatrix();
        cm.set(new float[] {
                            1, 0, 0, 0, r,
                            0, 1, 0, 0, g,
                            0, 0, 1, 0, b,
                            0, 0, 0, 1, 0 }); // last line is antialias
        paint.setColorFilter(new ColorMatrixColorFilter(cm));
        canvas.drawBitmap(myBitmap, toX, toY, paint);