Tech tip of this week

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); 
view.setBackgroundDrawable(image);


Sample code using tint attribute:

<LinearLayout
   xmlns:android="http://schemas.android.com/apk/res/android"
   android:orientation="vertical"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:gravity="center"
   android:id="@+id/sample_main_layout">
<ImageView
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:src="@drawable/unnamed"/>
<ImageView
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:src="@drawable/unnamed"
       android:tint="@color/red"/>
<ImageView
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:src="@drawable/unnamed"
       android:tint="@color/green"/>
</LinearLayout>

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

No comments:

Post a Comment