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

2k Views Asked by At

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?

3

There are 3 best solutions below

1
On BEST ANSWER

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);
2
On

You can not change colours of .png icons but you can change colour of vector icon in xml form. To change the colour of icon just import the icon with a different colour.

2
On

I am not much sure about your problem but whenever i need to change the color of .png images i just to be use tint method. you can see following code for help

XML CODE

<ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ss"
        android:tint="@color/colorPrimary"
        />

java Code

getBackground().setTint(tintColor);