205

I'm trying to change the color on a white marker image by code. I have read that the code below should change the color, but my marker remains white.

Drawable.setColorFilter( 0xffff0000, Mode.MULTIPLY )

Did I miss something? Is there any other way to change colors on my drawables located in my res folder?

3

20 Answers 20

351

Try this:

Drawable unwrappedDrawable = AppCompatResources.getDrawable(context, R.drawable.my_drawable); 
Drawable wrappedDrawable = DrawableCompat.wrap(unwrappedDrawable);
DrawableCompat.setTint(wrappedDrawable, Color.RED);    

Using DrawableCompat is important because it provides backwards compatibility and bug fixes on API 22 devices and earlier.

7
  • Hmm, the color remains white. Could it have to do with the hello mapview OverlayItems class that might be causing the problem? Its a regular drawable from my res folder, nothing special...
    – Johan
    Jul 7, 2012 at 16:27
  • 31
    You might prefer PorterDuff.Mode.SRC_IN if you want it to work with a wider range of source colors. Jul 16, 2015 at 19:27
  • PorterDuff.Mode.MULTIPLY did not changed anything for me ( Black star with transparent background). i used the PorterDuff.Mode.SRC_ATOP for coloring the actual bitmap. Mar 9, 2016 at 11:54
  • 1
    PorterDuffColorFilter constructor takes ARGB color format
    – RichX
    Mar 23, 2017 at 9:31
  • 3
    will be interesting to mutate the drawable with #mutate() to avoid share its state with any other drawable, otherwise if you reuse the drawable could have wrong color.
    – Ricard
    Mar 27, 2020 at 18:02
164

You can try this for svg vector drawable

DrawableCompat.setTint(
    DrawableCompat.wrap(myImageView.getDrawable()),
    ContextCompat.getColor(context, R.color.another_nice_color)
);
8
  • 7
    Best way I've seen for svg.
    – apSTRK
    Jan 18, 2017 at 21:44
  • 1
    prefer this over the accepted answer, although both will work, but with this one I don't have to worry about what drawable to set, i just get the one already there, and it's also backward compatible, great! Jun 29, 2017 at 20:17
  • 1
    Best answer when nothing worked iot work like a charm! Thanks a lot! Note: It also works for when you have a xml drawable in your imageView/AppCompatImageView
    – Sjd
    Sep 15, 2017 at 13:10
  • 1
    How to remove it programatically ? Oct 4, 2018 at 9:04
  • 3
    @HardikJoshi Documentation says: To clear the tint, pass null to Drawable#setTintList(ColorStateList)
    – arekolek
    Jan 11, 2019 at 15:55
37

You may need to call mutate() on the drawable or else all icons are affected.

Drawable icon = ContextCompat.getDrawable(getContext(), R.drawable.ic_my_icon).mutate();
TypedValue typedValue = new TypedValue();
getContext().getTheme().resolveAttribute(R.attr.colorIcon, typedValue, true);
icon.setColorFilter(typedValue.data, PorterDuff.Mode.SRC_ATOP);
1
  • 1
    What really make your answer incredible is mutate() that really what I was searching for. Thanks. Feb 11, 2021 at 5:06
34

You can try this for ImageView. using setColorFilter().

imageView.setColorFilter(ContextCompat.getColor(context, R.color.colorWhite));
22

Another way to do this on Lollipop, android 5.+ is setting a tint on a bitmap drawable like such:

<?xml version="1.0" encoding="utf-8"?>
<bitmap
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:src="@drawable/ic_back"
    android:tint="@color/red_tint"/>

This will work for you if you have a limited number of colors you want to use on your drawables. Check out my blog post for more information.

5
  • 2
    Nice! Btw, this seems to work fine on pre-Lollipop too. (Just tested this with minSdkVersion 16 and Android 4.1.1 device.)
    – Jonik
    Mar 3, 2015 at 12:16
  • When creating a bitmap this way, it does not stretch to fit the layout as it would when using android:background="...". Pretty strange!
    – Prince
    May 19, 2015 at 10:45
  • I think that's because you are not creating a nine patch here.
    – MinceMan
    May 19, 2015 at 12:39
  • Sorry this page does not exist =(
    – Linh
    Jul 29, 2016 at 7:41
  • @Jonik The answers in your provided question are irrelevant. This question is asking for the way to change Drawable's colour, not ImageView.
    – Antony.H
    Feb 2, 2017 at 4:45
13

I have wrote a generic function in which you can pass context, icon is id drawable/mipmap image icon and new color which you need for that icon.

This function returns a drawable.

public static Drawable changeDrawableColor(Context context,int icon, int newColor) {
    Drawable mDrawable = ContextCompat.getDrawable(context, icon).mutate(); 
    mDrawable.setColorFilter(new PorterDuffColorFilter(newColor, PorterDuff.Mode.SRC_IN)); 
    return mDrawable;
} 

changeDrawableColor(getContext(),R.mipmap.ic_action_tune, Color.WHITE);
0
10

You could try a ColorMatrixColorFilter, since your key color is white:

// Assuming "color" is your target color
float r = Color.red(color) / 255f;
float g = Color.green(color) / 255f;
float b = Color.blue(color) / 255f;

ColorMatrix cm = new ColorMatrix(new float[] {
        // Change red channel
        r, 0, 0, 0, 0,
        // Change green channel
        0, g, 0, 0, 0,
        // Change blue channel
        0, 0, b, 0, 0,
        // Keep alpha channel
        0, 0, 0, 1, 0,
});
ColorMatrixColorFilter cf = new ColorMatrixColorFilter(cm);
myDrawable.setColorFilter(cf);
0
10

This worked for me. Make sure to put "ff" between 0x and color code. Like this 0xff2196F3

Drawable mDrawable = ContextCompat.getDrawable(MainActivity.this,R.drawable.ic_vector_home);
                    mDrawable.setColorFilter(new
                            PorterDuffColorFilter(0xff2196F3,PorterDuff.Mode.SRC_IN));
1
  • Hi @Bek welcome to stackoverflow. If this worked for you, it would be very helpful to include a jsfiddle with minimal solution to show that. It will help the person who posted question to understand properly. Nov 15, 2017 at 4:21
6

Same as the accepted answer but a simpler convenience method:

val myDrawable = ContextCompat.getDrawable(context, R.drawable.my_drawable)
myDrawable.setColorFilter(Color.GREEN, PorterDuff.Mode.SRC_IN)
setCompoundDrawablesWithIntrinsicBounds(myDrawable, null, null, null)

Note, the code here is Kotlin.

6

For those who use Kotlin a simple extension function:

fun Drawable.tint(context: Context,  @ColorRes color: Int) {
    DrawableCompat.setTint(this, context.resources.getColor(color, context.theme))
}

and then simply do

background.tint(context, R.color.colorPrimary)
0
5

Use this: For java

view.getBackground().setColorFilter(Color.parseColor("#343434"), PorterDuff.Mode.SRC_OVER)

for Kotlin

view.background.setColorFilter(Color.parseColor("#343434"),PorterDuff.Mode.SRC_OVER)

you can use PorterDuff.Mode.SRC_ATOP, if your background has rounded corners etc.

3

You may want to try Mode.LIGHTEN or Mode.DARKEN. The Android Javadocs are horrible at explaining what the PorterDuff Modes do. You can take a look at them here: PorterDuff | Android

I suggest looking around at Compositing on Mozilla's site here. (They don't have all the modes that android does but they have a lot of them)

3

You can change your drawable color in this way:

background = view.findViewById(R.id.background)

val uDrawable = AppCompatResources.getDrawable(view.context, R.drawable.background)
uDrawable?.let {
      val wDrawable = DrawableCompat.wrap(it)
      DrawableCompat.setTint(wDrawable, ContextCompat.getColor(view.context, 
                                                      color /*specify your int color code*/))
      background.background = wDrawable
}
2

Syntax

"your image name".setColorFilter("your context".getResources().getColor("color name"));

Example

myImage.setColorFilter(mContext.getResources().getColor(R.color.deep_blue_new));
2

SDK >= 21 one line myIconImageView.getDrawable().setTint(getResources().getColor(myColor))

1
  • Pretty nice, I recommend to use Drawable newDrawable = myDrawable.mutate().setTint(getResources().getColor(myColor)) to avoid changing it globally
    – FreddaP
    Mar 3, 2022 at 14:01
1

Kotlin Version

val unwrappedDrawable =
            AppCompatResources.getDrawable(this, R.drawable.your_drawable)
        val wrappedDrawable = DrawableCompat.wrap(unwrappedDrawable!!)
DrawableCompat.setTint(wrappedDrawable, Color.RED)
0

This is what i did:

public static Drawable changeDrawableColor(int drawableRes, int colorRes, Context context) {
    //Convert drawable res to bitmap
    final Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), drawableRes);
    final Bitmap resultBitmap = Bitmap.createBitmap(bitmap, 0, 0,
            bitmap.getWidth() - 1, bitmap.getHeight() - 1);
    final Paint p = new Paint();
    final Canvas canvas = new Canvas(resultBitmap);
    canvas.drawBitmap(resultBitmap, 0, 0, p);

    //Create new drawable based on bitmap
    final Drawable drawable = new BitmapDrawable(context.getResources(), resultBitmap);
    drawable.setColorFilter(new
            PorterDuffColorFilter(context.getResources().getColor(colorRes), PorterDuff.Mode.MULTIPLY));
    return drawable;
}
0

Create Method like this :

//CHANGE ICON COLOR
private void changeIconColor(Context context ,int drawable){
    Drawable unwrappedDrawable = AppCompatResources.getDrawable(context, drawable);
    assert unwrappedDrawable != null;
    Drawable wrappedDrawable = DrawableCompat.wrap(unwrappedDrawable);
    DrawableCompat.setTint(wrappedDrawable, getResources().getColor(R.color.colorAccent));
}

and use it like it :

    changeIconColor(this,R.drawable.ic_home);
0

Easiest Way to do it :

imageView.setColorFilter(Color.rgb(r, g b));

or

imageView.setColorFilter(Color.argb(a, r, g, b));

a, r, g, b : Color argb values.

1
  • This will only work if the OP would have be using imageViews instead of drawables. Dec 14, 2019 at 10:54
0

Long story short :

May 2023 Kotlin (all APIs):

 DrawableCompat.wrap
     (AppCompatResources.getDrawable(ctx, R.drawable.myDrawable)!!)
    .mutate()
    .also { DrawableCompat.setTint(it,0xFFff0000.toInt()) }

⚠ don't forget the mutate, a mutable drawable is guaranteed to not share its state with any other! This is especially useful when you need to modify properties of drawables loaded from resources. By default, all drawables instances loaded from the same resource share a common state; if you modify the state of one instance, all the other instances will receive the same modification. Calling this method on a mutable Drawable will have no effect.

Old - Java :

public Drawable getColoredDrawable(@DrawableRes int resid,int color){
    Drawable drawable= ContextCompat.getDrawable(context, resid).mutate();
    DrawableCompat.setTint(drawable, color);
    return drawable;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.