头像由彩色变灰色有两种实现方式:
方法1把图片彩色图转换为纯黑白二色:
/**
* 将彩色图转换为纯黑白二色
*
* @param 位图
* @return 返回转换好的位图
*/
private Bitmap convertToBlackWhite(Bitmap bmp) {
int width = bmp.getWidth(); // 获取位图的宽
int height = bmp.getHeight(); // 获取位图的高
int[] pixels = new int[width * height]; // 通过位图的大小创建像素点数组
bmp.getPixels(pixels, 0, width, 0, 0, width, height);
int alpha = 0xFF << 24;
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
int grey = pixels[width * i + j];
// 分离三原色
int red = ((grey & 0x00FF0000) >> 16);
int green = ((grey & 0x0000FF00) >> 8);
int blue = (grey & 0x000000FF);
// 转化成灰度像素
grey = (int) (red * 0.3 + green * 0.59 + blue * 0.11);
grey = alpha | (grey << 16) | (grey << 8) | grey;
pixels[width * i + j] = grey;
}
}
// 新建图片
Bitmap newBmp = Bitmap.createBitmap(width, height, Config.RGB_565);
// 设置图片数据
newBmp.setPixels(pixels, 0, width, 0, 0, width, height);
Bitmap resizeBmp = ThumbnailUtils.extractThumbnail(newBmp, 380, 460);
return resizeBmp;
}
方法2使用ColorMatrix:
ColorMatrix类有一个内置的方法可用于改变饱和度。
传入一个大于1的数字将增加饱和度,而传入一个0~1之间的数字会减少饱和度。0值将产生一幅灰度图像。
代码如下:
ImageView image1 = (ImageView) findViewById(R.id.imageView1);
ColorMatrix matrix = new ColorMatrix();
matrix.setSaturation(0);
ColorMatrixColorFilter filter = new ColorMatrixColorFilter(matrix);
image1.setColorFilter(filter);
这里再扩展下,有时候我们需要把一张图变暗,也有两种方式可以实现。
方法1:
ImageView image3 = (ImageView) findViewById(R.id.imageView3);
Drawable drawable = getResources().getDrawable(R.drawable.mm);
drawable.setColorFilter(Color.GRAY, PorterDuff.Mode.MULTIPLY);
image3.setImageDrawable(drawable);
方法2:把要显示的图片作为background,把变暗的图片或颜色设为src,就可以实现变暗的效果。
<ImageView
android:id="@+id/imageView4"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_marginLeft="10dp"
android:background="@drawable/mm2"
android:src="#77000000" />
上图:
Demo下载:https://github.com/xie2000/ColorMatrixDemo
QQ交流群:6399844