实现类似QQ离线用户头像彩色变灰色的效果
生活随笔
收集整理的這篇文章主要介紹了
实现类似QQ离线用户头像彩色变灰色的效果
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
頭像由彩色變灰色有兩種實(shí)現(xiàn)方式:
方法1把圖片彩色圖轉(zhuǎn)換為純黑白二色:
/*** 將彩色圖轉(zhuǎn)換為純黑白二色* * @param 位圖* @return 返回轉(zhuǎn)換好的位圖*/private Bitmap convertToBlackWhite(Bitmap bmp) {int width = bmp.getWidth(); // 獲取位圖的寬int height = bmp.getHeight(); // 獲取位圖的高int[] pixels = new int[width * height]; // 通過位圖的大小創(chuàng)建像素點(diǎn)數(shù)組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);// 轉(zhuǎn)化成灰度像素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);// 設(shè)置圖片數(shù)據(jù)newBmp.setPixels(pixels, 0, width, 0, 0, width, height);Bitmap resizeBmp = ThumbnailUtils.extractThumbnail(newBmp, 380, 460);return resizeBmp;}
方法2使用ColorMatrix:
ColorMatrix類有一個(gè)內(nèi)置的方法可用于改變飽和度。
傳入一個(gè)大于1的數(shù)字將增加飽和度,而傳入一個(gè)0~1之間的數(shù)字會(huì)減少飽和度。0值將產(chǎn)生一幅灰度圖像。
代碼如下:
ImageView image1 = (ImageView) findViewById(R.id.imageView1);ColorMatrix matrix = new ColorMatrix();matrix.setSaturation(0);ColorMatrixColorFilter filter = new ColorMatrixColorFilter(matrix);image1.setColorFilter(filter);
這里再擴(kuò)展下,有時(shí)候我們需要把一張圖變暗,也有兩種方式可以實(shí)現(xiàn)。
方法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,把變暗的圖片或顏色設(shè)為src,就可以實(shí)現(xiàn)變暗的效果。
<ImageViewandroid: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
總結(jié)
以上是生活随笔為你收集整理的实现类似QQ离线用户头像彩色变灰色的效果的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 2017百度之星总结
- 下一篇: 记2018湖南CCF-CCSP