Tint the drawable with color - Android android.graphics.drawable

Android examples for android.graphics.drawable:Drawable

Description

Tint the drawable with color

Demo Code

import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.ColorFilter;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffColorFilter;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;

public class Main{

    /**/*w w w  .j ava  2  s . c o  m*/
     * Tint the drawable resource with color
     *
     * @param res resources location
     * @param resId drawable resource id
     * @param tint color to apply to the image
     * @return the drawable after tint as a new copy, original resource will not be changed
     */
    public static Drawable setTint(Resources res, int resId, int tint) {
        Bitmap bitmap = BitmapFactory.decodeResource(res, resId);
        // make a copy of the drawable object
        Drawable bitmapDrawable = new BitmapDrawable(res, bitmap);
        // setup color filter for tinting
        ColorFilter cf = new PorterDuffColorFilter(tint,
                PorterDuff.Mode.SRC_IN);
        bitmapDrawable.setColorFilter(cf);

        return bitmapDrawable;
    }
    /**
     * Tint the drawable with color
     *
     * @param drawable to be tint
     * @param tint color to apply to the image
     * @return the drawable after tint as a new copy, original resource will not be changed
     */
    public static Drawable setTint(Drawable drawable, int tint) {
        // clone the drawable
        Drawable clone = drawable.mutate();
        // setup color filter for tinting
        ColorFilter cf = new PorterDuffColorFilter(tint,
                PorterDuff.Mode.SRC_IN);
        if (clone != null)
            clone.setColorFilter(cf);

        return clone;
    }

}

Related Tutorials