实现类似QQ离线用户头像彩色变灰色的效果
生活随笔
收集整理的這篇文章主要介紹了
实现类似QQ离线用户头像彩色变灰色的效果
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
頭像由彩色變灰色有兩種實現方式:
方法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,就可以實現變暗的效果。
<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
總結
以上是生活随笔為你收集整理的实现类似QQ离线用户头像彩色变灰色的效果的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 2017百度之星总结
- 下一篇: 记2018湖南CCF-CCSP