Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change colors of a Drawable in Android?

People also ask

How do you change the color of a drawable icon?

This example demonstrates how to change the colors of a Drawable in Android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml.

What is ColorDrawable?

android.graphics.drawable.ColorDrawable. A specialized Drawable that fills the Canvas with a specified color. Note that a ColorDrawable ignores the ColorFilter. It can be defined in an XML file with the <color> element.

What is drawable XML file?

A drawable resource is a general concept for a graphic that can be drawn to the screen and which you can retrieve with APIs such as getDrawable(int) or apply to another XML resource with attributes such as android:drawable and android:icon . There are several different types of drawables: Bitmap File.


I think you can actually just use Drawable.setColorFilter( 0xffff0000, Mode.MULTIPLY ). This would set white pixels to red but I don't think it would affect the transparent pixels.

See Drawable#setColorFilter


Give this code a try:

ImageView lineColorCode = (ImageView)convertView.findViewById(R.id.line_color_code);
int color = Color.parseColor("#AE6118"); //The color u want             
lineColorCode.setColorFilter(color);

I know this question was ask way before Lollipop but I would like to add a nice way to do this on Android 5.+. You make an xml drawable that references the original one and set tint on it 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"/>

The new support v4 bring tint back to api 4.

you can do it like this

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

If you have a drawable that's a solid color and you want to change it to a differnet solid color, you can use a ColorMatrixColorFilter. Transparency is preserved.

int iColor = Color.parseColor(color);

int red   = (iColor & 0xFF0000) / 0xFFFF;
int green = (iColor & 0xFF00) / 0xFF;
int blue  = iColor & 0xFF;

float[] matrix = { 0, 0, 0, 0, red,
                   0, 0, 0, 0, green,
                   0, 0, 0, 0, blue,
                   0, 0, 0, 1, 0 };

ColorFilter colorFilter = new ColorMatrixColorFilter(matrix);
drawable.setColorFilter(colorFilter);

I also use ImageView for icons (in ListView or settings screen). But I think there is much simpler way to do that.

Use tint to change the color overlay on your selected icon.

In xml,

android:tint="@color/accent"
android:src="@drawable/ic_event" 

works fine since it comes from AppCompat