1. 程式人生 > >如何實現Android 佈局背景模糊化處理

如何實現Android 佈局背景模糊化處理

在模仿 IOS 密碼輸入頁面的時候發現其背景有模糊處理,於是瞭解了一下並記錄下來,以便使用.在Android 中具體實現方法如下

查考 http://www.cnblogs.com/lipeil/p/3997992.html

private void applyBlur() { 
	  
	// 獲取桌布管理器  
	WallpaperManager wallpaperManager = WallpaperManager.getInstance(this.getContext());  
	// 獲取當前桌布  
	Drawable wallpaperDrawable = wallpaperManager.getDrawable();  
	// 將Drawable,轉成Bitmap  
	Bitmap bmp = ((BitmapDrawable) wallpaperDrawable).getBitmap();  
	
	blur(bmp); 
} 

下面之所以要進行small 和big的處理,是因為僅僅靠ScriptIntrinsicBlur  來處理模式,不能到達更模式的效果,如果需要加深模式效果就需要先把背景圖片縮小,在處理完之後再放大.這個可以使用Matrix 來實現,而且這樣可以縮短模糊化得時間

@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1) 
private void blur(Bitmap bkg) { 
	long startMs = System.currentTimeMillis(); 
	float radius = 20; 

	bkg = small(bkg);
	Bitmap bitmap = bkg.copy(bkg.getConfig(), true);

	final RenderScript rs = RenderScript.create(this.getContext());
	final Allocation input = Allocation.createFromBitmap(rs, bkg, Allocation.MipmapControl.MIPMAP_NONE,
			Allocation.USAGE_SCRIPT);
	final Allocation output = Allocation.createTyped(rs, input.getType());
	final ScriptIntrinsicBlur script = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));
	script.setRadius(radius);
	script.setInput(input);
	script.forEach(output);
	output.copyTo(bitmap);

	bitmap = big(bitmap);
	setBackground(new BitmapDrawable(getResources(), bitmap)); 
	rs.destroy(); 
	Log.d("zhangle","blur take away:" + (System.currentTimeMillis() - startMs )+ "ms"); 
} 

private static Bitmap big(Bitmap bitmap) {
	  Matrix matrix = new Matrix(); 
	  matrix.postScale(4f,4f); //長和寬放大縮小的比例
	  Bitmap resizeBmp = Bitmap.createBitmap(bitmap,0,0,bitmap.getWidth(),bitmap.getHeight(),matrix,true);
	  return resizeBmp;
 }

 private static Bitmap small(Bitmap bitmap) {
	  Matrix matrix = new Matrix(); 
	  matrix.postScale(0.25f,0.25f); //長和寬放大縮小的比例
	  Bitmap resizeBmp = Bitmap.createBitmap(bitmap,0,0,bitmap.getWidth(),bitmap.getHeight(),matrix,true);
	  return resizeBmp;
}