Change png icon color in from drawable resources

14,428

Solution 1

You can use a ColorFilter to change the icons color at runtime.

Try something like this:

    Drawable mIcon= ContextCompat.getDrawable(getActivity(), R.drawable.your_icon);
    mIcon.setColorFilter(ContextCompat.getColor(getActivity(), R.color.new_color), PorterDuff.Mode.MULTIPLY);
    mImageView.setImageDrawable(mIcon);

Solution 2

A good helper function for this is,

public Drawable getTintedDrawable(Resources res,
    @DrawableRes int drawableResId, @ColorRes int colorResId) {
    Drawable drawable = res.getDrawable(drawableResId);
    int color = res.getColor(colorResId);
    drawable.setColorFilter(color, PorterDuff.Mode.SRC_IN);
    return drawable;
}

Fast Android asset theming with ColorFilter - Dan Lew

Solution 3

you can try this

Drawable mDrawable = context.getResources().getDrawable(R.drawable.yourdrawable); 
mDrawable.setColorFilter(new 
PorterDuffColorFilter(0xffff00,PorterDuff.Mode.MULTIPLY));

Solution 4

Try using this static method:

public static Drawable changeDrawableColor(Drawable drawable, int color) {
    drawable = DrawableCompat.wrap(drawable);
    DrawableCompat.setTint(drawable, color);
    return drawable;
}

The color parameter could be a color from your resources.

Solution 5

Drawable mDrawable = context.getResources().getDrawable(R.drawable.balloons); 
mDrawable.setColorFilter(new 
PorterDuffColorFilter(0xffff00,PorterDuff.Mode.LIGHTEN));

Try the above You can Play with PorterDuffColorFilter(0xffff00,PorterDuff.Mode.LIGHTEN) You can use Black etc.

Share:
14,428
Igor
Author by

Igor

I am trying to program on Java and android.

Updated on June 08, 2022

Comments

  • Igor
    Igor almost 2 years

    I have an icon in png in drawable. It's black with the transparent background. How can I change the icon color without adding another drawable?

  • syed dastagir
    syed dastagir over 3 years
    backgroundTint didn't work for me, currently using Android Studio 4.0