1. 程式人生 > >Android——圖片設定為高斯模糊效果(ImageView)

Android——圖片設定為高斯模糊效果(ImageView)

效果圖:


//模糊
Resources res = ShowActivity.this.getResources();
//拿到初始圖
Bitmap bmp= BitmapFactory.decodeResource(res,R.mipmap.user);
//處理得到模糊效果的圖
Bitmap blurBitmap = ImageFilter.blurBitmap(this, bmp, 20f);
img.setImageBitmap(blurBitmap);

ImageFilter.java

public class ImageFilter {
    //圖片縮放比例
private static final float 
BITMAP_SCALE = 0.4f; /** * 模糊圖片的具體方法 * * @param context 上下文物件 * @param image 需要模糊的圖片 * @return 模糊處理後的圖片 */ public static Bitmap blurBitmap(Context context, Bitmap image, float blurRadius) { // 計算圖片縮小後的長寬 int width = Math.round(image.getWidth() * BITMAP_SCALE); int height = Math
.round(image.getHeight() * BITMAP_SCALE); // 將縮小後的圖片做為預渲染的圖片 Bitmap inputBitmap = Bitmap.createScaledBitmap(image, width, height, false); // 建立一張渲染後的輸出圖片 Bitmap outputBitmap = Bitmap.createBitmap(inputBitmap); // 建立RenderScript核心物件 RenderScript rs = RenderScript.create(context); //
建立一個模糊效果的RenderScript的工具物件 ScriptIntrinsicBlur blurScript = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs)); // 由於RenderScript並沒有使用VM來分配記憶體,所以需要使用Allocation類來建立和分配記憶體空間 // 建立Allocation物件的時候其實記憶體是空的,需要使用copyTo()將資料填充進去 Allocation tmpIn = Allocation.createFromBitmap(rs, inputBitmap); Allocation tmpOut = Allocation.createFromBitmap(rs, outputBitmap); // 設定渲染的模糊程度, 25f是最大模糊度 blurScript.setRadius(blurRadius); // 設定blurScript物件的輸入記憶體 blurScript.setInput(tmpIn); // 將輸出資料儲存到輸出記憶體中 blurScript.forEach(tmpOut); // 將資料填充到AllocationtmpOut.copyTo(outputBitmap); return outputBitmap; } }