How to tint a Bitmap to a solid color

折月煮酒 提交于 2019-12-09 14:14:21

问题


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.


回答1:


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);



回答2:


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;
}



回答3:


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" />


来源:https://stackoverflow.com/questions/6331906/how-to-tint-a-bitmap-to-a-solid-color

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!