标签:setsaturation 图片 android colormatrix bitmap
原图:
效果图:
实现以上效果其实很简单,直接上代码:
public class MainActivity extends Activity { private Button btn_start; private ImageView img; private Bitmap bitmap; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.image_layout); initView(); } private void initView() { img = (ImageView) findViewById(R.id.iv_image); btn_start = (Button) findViewById(R.id.btn_start); bitmap = ((BitmapDrawable) img.getDrawable()).getBitmap(); btn_start.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Bitmap bm = ImageTools.toGrayscale(bitmap); img.setImageBitmap(bm); } }); } }
/** */ /** * 图片去色,返回灰度图片 * * @param bmpOriginal * 传入的图片 * @return 去色后的图片 */ public static Bitmap toGrayscale(Bitmap bmp) { if (bmp != null) { int width, height; Paint paint = new Paint(); height = bmp.getHeight(); width = bmp.getWidth(); Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565); Canvas c = new Canvas(bm); ColorMatrix cm = new ColorMatrix(); cm.setSaturation(0); ColorMatrixColorFilter f = new ColorMatrixColorFilter(cm); paint.setColorFilter(f); c.drawBitmap(bmp, 0, 0, paint); return bm; }else{ return bmp; } }
setSaturation源码是如何实现的:
public void setSaturation(float sat) { reset(); float[] m = mArray; final float invSat = 1 - sat; final float R = 0.213f * invSat; final float G = 0.715f * invSat; final float B = 0.072f * invSat; m[0] = R + sat; m[1] = G; m[2] = B; m[5] = R; m[6] = G + sat; m[7] = B; m[10] = R; m[11] = G; m[12] = B + sat; }
我们接着看上面的代码,第一步调用了reset方法,我们看下reset方法:
/** * Set this colormatrix to identity: * [ 1 0 0 0 0 - red vector * 0 1 0 0 0 - green vector * 0 0 1 0 0 - blue vector * 0 0 0 1 0 ] - alpha vector */ public void reset() { final float[] a = mArray; for (int i = 19; i > 0; --i) { a[i] = 0; } a[0] = a[6] = a[12] = a[18] = 1; }
接着看就会发现,给图片去色,就是改变颜色矩阵中的值。
将setSaturation中的值设成3看看:
public static Bitmap toGrayscale(Bitmap bmp) { if (bmp != null) { int width, height; Paint paint = new Paint(); height = bmp.getHeight(); width = bmp.getWidth(); Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565); Canvas c = new Canvas(bm); ColorMatrix cm = new ColorMatrix(); cm.setSaturation(3); ColorMatrixColorFilter f = new ColorMatrixColorFilter(cm); paint.setColorFilter(f); c.drawBitmap(bmp, 0, 0, paint); return bm; }else{ return bmp; } }
通过改变颜色矩阵值,可以实现一些比较好看的效果。
转载请注明出处:http://blog.csdn.net/hai_qing_xu_kong/article/details/45244049 情绪控_
一起学android之给图片去色,返回灰度图片以及ColorMatrix中setSaturation方法的用法(34)
标签:setsaturation 图片 android colormatrix bitmap
原文地址:http://blog.csdn.net/hai_qing_xu_kong/article/details/45244049