Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to tint a Bitmap to a solid color

How would one go about tinting a Bitmap to a solid color, effectively replacing all pixels that have an alpha > 0 to a given RGB value? In addition how to do the same thing, but keeping the alpha for every pixel? I'm not looking for per-pixel operations as they tend to be slow.

I tried using a ColorMatrixColorFilter and a ColorFilter, which do tint the Bitmap, but they colorize instead of performing a 100% tint.

like image 859
Will Kru Avatar asked Jun 13 '11 14:06

Will Kru


3 Answers

I solved this by using a PorterDuffColorFilter

Paint paint = new Paint();
paint.setColorFilter(new PorterDuffColorFilter(targetColor, PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(resource, matrix, paint);
like image 63
Will Kru Avatar answered Nov 03 '22 04:11

Will Kru


Just to give a more complete answer.

This will take a bitmap and output a new tinted bitmap:

public static Bitmap tintImage(Bitmap bitmap, int color) {
    Paint paint = new Paint();
    paint.setColorFilter(new PorterDuffColorFilter(color, PorterDuff.Mode.SRC_IN));
    Bitmap bitmapResult = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmapResult);
    canvas.drawBitmap(bitmap, 0, 0, paint);
    return bitmapResult;
}
like image 34
joaomgcd Avatar answered Nov 03 '22 03:11

joaomgcd


If your bitmap is a drawable that you want to use in a layout, then you can make a new drawable (.xml) that references your original drawable (e.g .png).

<?xml version="1.0" encoding="utf-8"?>
<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
    android:src="@drawable/plus"
     android:tint="#2c53e5" />
like image 42
Johan Franzén Avatar answered Nov 03 '22 03:11

Johan Franzén