首页 > 代码库 > 黑白效果函数

黑白效果函数

// 黑白效果函数
public static Bitmap changeToGray(Bitmap bitmap,boolean r, boolean g, boolean b) {

int width, height;
width = bitmap.getWidth();
height = bitmap.getHeight();

Bitmap grayBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
Canvas canvas = new Canvas(grayBitmap);
Paint paint = new Paint();
paint.setAntiAlias(true); // 设置抗锯齿

//方法一
ColorMatrix colorMatrix = new ColorMatrix();
colorMatrix.setSaturation(0);
/* 方法二
* ColorMatrix colorMatrix = new ColorMatrix();
float[] m = colorMatrix.getArray();
setColorFilterMatrix(m, r, g, b);*/

ColorMatrixColorFilter filter = new ColorMatrixColorFilter(colorMatrix);

paint.setColorFilter(filter);
canvas.drawBitmap(bitmap, 0, 0, paint);

return grayBitmap;
}

public static void setColorFilterMatrix(float[] m, boolean r, boolean g, boolean b) {
final float R = 0.213f;
final float G = 0.715f;
final float B = 0.072f;

m[0] = 0;
m[6] = 0;
m[12] = 0;

if (r) {
m[0] = R; m[1] = G; m[2] = B;
}
if (g) {
m[5] = R; m[6] = G; m[7] = B;
}
if (b) {
m[10] = R; m[11] = G; m[12] = B;
}
}