直接上代码
public void change(View v) {
Drawable drawAble = img.getBackground();
img.setImageBitmap(toGrayscale(drawableToBitmap(img.getDrawable())));
}
//置灰 RGB_565会使整个背景都变黑
private Bitmap drawableToBitmap(Drawable drawable) {
//Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(),drawable.getIntrinsicHeight(),drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888: Bitmap.Config.RGB_565);
Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(),drawable.getIntrinsicHeight(),Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),drawable.getIntrinsicHeight());
drawable.draw(canvas);
return bitmap;
}
private Bitmap toGrayscale(Bitmap bmpOriginal) {
int width, height;
height = bmpOriginal.getHeight();
width = bmpOriginal.getWidth();
Bitmap bmpGrayscale = Bitmap.createBitmap(width, height,Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(bmpGrayscale);
Paint paint = new Paint();
ColorMatrix cm = new ColorMatrix();
cm.setSaturation(0);
ColorMatrixColorFilter f = new ColorMatrixColorFilter(cm);
paint.setColorFilter(f);
c.drawBitmap(bmpOriginal, 0, 0, paint);
return bmpGrayscale;
}
混淆的地方
- Bitmap.Config.ARGB_8888代表32位ARGB位图
- ALPHA_8 代表8位Alpha位图
- RGB_565 代表8位RGB位图
- ALPHA_8 代表8位Alpha位图
9/25/2015 3:13:56 PM