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.
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);
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;
}
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" />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With