Change drawable color programmatically
Asked Answered
C

20

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?

Charliecharline answered 7/7, 2012 at 16:2 Comment(3)
accepted answer didn't work for me..used this How to Answer[1], [1]: #5941325Esdraelon
I think all the answers here change the background color, but not color of the image. Im i right? can anyone tell me please? I tried all the solutions here and also on same questions on stackoverflow, but they change only background color in may case. So i think, we can only change background color, but not the images color. I'm I right?Greeting
Check this answer: https://mcmap.net/q/129225/-drawable-tinting-in-recyclerview-for-pre-lollipopHoneysucker
W
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.

Weitzman answered 7/7, 2012 at 16:12 Comment(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...Charliecharline
You might prefer PorterDuff.Mode.SRC_IN if you want it to work with a wider range of source colors.Apsis
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.Enginery
There's also a convenience method you can use: setColorFilter(Color.WHITE, PorterDuff.Mode.SRC_IN)Ramify
PorterDuffColorFilter constructor takes ARGB color formatMestizo
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.Savoirfaire
The drawables are shared amongst all getDrawable from resources, hence the mutate() call is required to be able to change the tint of a drawable, without altering all the drawables associates with that resource ID, see https://mcmap.net/q/99592/-how-to-change-colors-of-a-drawable-in-androidSavoirfaire
P
164

You can try this for svg vector drawable

DrawableCompat.setTint(
    DrawableCompat.wrap(myImageView.getDrawable()),
    ContextCompat.getColor(context, R.color.another_nice_color)
);
Phraseogram answered 6/10, 2016 at 9:40 Comment(8)
Best way I've seen for svg.Impulsive
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!Excel
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/AppCompatImageViewYodel
How to remove it programatically ?Sopor
@HardikJoshi Documentation says: To clear the tint, pass null to Drawable#setTintList(ColorStateList)Faustino
Unfortunately, this overrides the set stroke in the xml file, whereas the color filter option doesn'tArmstead
Correction, it only does so when not setting a mode. When using DrawableCompat.setTintMode(bgDrawable, PorterDuff.Mode.MULTIPLY) before applying the tint, it works the same as color filter.Armstead
Remember to use mutate() or else you'd change the colour of the drawable globally!Courtroom
A
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);
Angelicangelica answered 21/1, 2016 at 7:11 Comment(1)
What really make your answer incredible is mutate() that really what I was searching for. Thanks.Piquet
C
34

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

imageView.setColorFilter(ContextCompat.getColor(context, R.color.colorWhite));
Cauley answered 16/1, 2018 at 9:3 Comment(0)
S
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.

Sacramentalist answered 9/12, 2014 at 17:3 Comment(5)
Nice! Btw, this seems to work fine on pre-Lollipop too. (Just tested this with minSdkVersion 16 and Android 4.1.1 device.)Worried
When creating a bitmap this way, it does not stretch to fit the layout as it would when using android:background="...". Pretty strange!Angieangil
I think that's because you are not creating a nine patch here.Sacramentalist
Sorry this page does not exist =(Jaenicke
@Worried The answers in your provided question are irrelevant. This question is asking for the way to change Drawable's colour, not ImageView.Jeopardy
M
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);
Moonstruck answered 20/3, 2017 at 8:28 Comment(0)
M
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);
Mlawsky answered 7/7, 2012 at 16:38 Comment(0)
R
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));
Rudderhead answered 15/11, 2017 at 4:14 Comment(1)
Hi @Rudderhead 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.Bentinck
R
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.

Ramify answered 18/5, 2017 at 17:51 Comment(0)
T
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)
Torture answered 8/7, 2020 at 20:44 Comment(0)
S
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.

Scriptural answered 12/7, 2019 at 19:55 Comment(0)
T
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)

Transferor answered 7/7, 2012 at 16:12 Comment(0)
R
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
}
Rianon answered 3/3, 2021 at 14:46 Comment(0)
B
2

Syntax

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

Example

myImage.setColorFilter(mContext.getResources().getColor(R.color.deep_blue_new));
Biodegradable answered 3/5, 2019 at 10:6 Comment(0)
M
2

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

Mcinnis answered 5/7, 2021 at 3:21 Comment(1)
Pretty nice, I recommend to use Drawable newDrawable = myDrawable.mutate().setTint(getResources().getColor(myColor)) to avoid changing it globallySickening
H
1

Kotlin Version

val unwrappedDrawable =
            AppCompatResources.getDrawable(this, R.drawable.your_drawable)
        val wrappedDrawable = DrawableCompat.wrap(unwrappedDrawable!!)
DrawableCompat.setTint(wrappedDrawable, Color.RED)
Hoxie answered 17/3, 2022 at 16:32 Comment(0)
S
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;
}
Spermatozoon answered 16/5, 2016 at 16:40 Comment(0)
M
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);
Michel answered 2/9, 2019 at 16:38 Comment(0)
F
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.

Funicle answered 27/11, 2019 at 11:35 Comment(1)
This will only work if the OP would have be using imageViews instead of drawables.Bouley
H
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;
}
Hedwighedwiga answered 30/5, 2021 at 7:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.