原图:
效果图:
实现以上效果其实很简单,直接上代码:
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);
}
});
}
}
看下ImageTools工具类中的方法:
/** */
/**
* 图片去色,返回灰度图片
*
* @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;
}
}
实现去色重点用到了ColorMatrix类中的setSaturation方法,如果去查看官网API的话,这个方法下有这么一段说明:
-
Set the matrix to affect the saturation of colors. A value of 0 maps the color to gray-scale. 1 is identity.
意思是去设置颜色矩阵的饱和度,0是灰色的,1是原图,那这个方法是不是只能设置0或1呢?其实不是,我们看下
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;
}
关于设置图片颜色的原理请参看《
一起学android之利用ColorMatrix进行图片的各种特效处理(32)
》
我们接着看上面的代码,第一步调用了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 情绪控_