Android: How to change Drawable color

With Android 5.0 (API level 21) and above, you can tint bitmaps and nine-patches defined as alpha masks. You can tint them with color resources. This makes it possible for you to create assets once and color them in your layout to match your theme.

You no longer have to create multiple versions of your assets to simply change their colors.
There's two problems with ImageView's tint, though, which is why you should avoid it:

  • ImageView's tint mixes the tint color with the original asset. What you want is for the tint color to take over entirely; instead it applies the tint on top of the existing color. So, for example, if the source asset is black, and you want it to be #77FFFFFF (a translucent shade of white), you'll actually end up getting that shade of white with a black background beneath it. 
  • android:tint is limited to ImageView.

To avoid above problems, we can use setColorFilter() method.

Resources res = getResources(); 
Drawable image= res.getDrawable(R.drawable.image); 
int color = res.getColor(R.color.primary); 
image.setColorFilter(color, PorterDuff.Mode.SRC_IN); 

Sample code using tint attribute:


If you observe in below screen, with single image created two different images with different colors.

No comments:

Post a Comment