導語:
用過小米電視的小伙伴都知道,高斯模糊在小米上得到了廣泛的運用,比如小米電視的設置界面.那么什么是高斯模糊,怎么樣做高斯模糊,這篇文章給你揭曉.
什么是高斯模糊
高斯模糊(英語:Gaussian Blur)唱歧,也叫高斯平滑住诸,是在Adobe Photoshop辰狡、GIMP以及Paint.NET等圖像處理軟件中廣泛使用的處理效果肺魁,通常用它來減少圖像噪聲以及降低細節(jié)層次铅搓。
高斯模糊給人的感覺是一層蒙版,這樣的話不會讓背景過于單調.
Android中實現高斯模糊的方式
在Adnroid 中拗慨,現在常用的圖片高斯模糊技術有三種:RenderScript 、fastBlur京景、對RenderScript和fastBlur的優(yōu)化.簡書上有一篇文章介紹了Android對高斯模糊的實現Android 圖片高斯模糊解決方案,這里講的比較詳細,具體原理可以參考這里.
AndroidTv中如何實現背景的高斯模糊.
在文章首的圖片實現了dialog背景的高斯模糊,實現背景的高斯模糊需要以下幾個步驟.
- 對背景截圖
/**
* 獲取整個窗口的截圖
*
* @param context
* @return
*/
@SuppressLint("NewApi")
private static Bitmap captureScreen(Activity context) {
if (view != null){
//清空緩沖
view.destroyDrawingCache();
}
view = context.getWindow().getDecorView();
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
Bitmap bmp = view.getDrawingCache();
if (bmp == null) {
return null;
}
bmp.setHasAlpha(false);
bmp.prepareToDraw();
return bmp;
}
- 對截圖進行高斯模糊化
/**
* 返回高斯模糊的圖片效果
*
* @param context
* @param bitmap
* @param radius
* @return
*/
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
public static Bitmap blur(Context context, Bitmap bitmap, float radius) {
// 創(chuàng)建輸出圖片
Bitmap output = Bitmap.createBitmap(bitmap);
// 構建一個RenderScript對象
RenderScript rs = RenderScript.create(context);
// 創(chuàng)建高斯模糊腳本
ScriptIntrinsicBlur gaussianBlue = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));
// 創(chuàng)建用于輸入的腳本類型
Allocation allIn = Allocation.createFromBitmap(rs, bitmap);
// 創(chuàng)建用于輸出的腳本類型
Allocation allOut = Allocation.createFromBitmhttps://github.com/songwenju/CustomTvRecyclerView.ap(rs, output);
// 設置模糊半徑迈勋,范圍0f<radius<=25f
gaussianBlue.setRadius(radius);
// 設置輸入腳本類型
gaussianBlue.setInput(allIn);
// 執(zhí)行高斯模糊算法,并將結果填入輸出腳本類型中
gaussianBlue.forEach(allOut);
// 將輸出內存編碼為Bitmap醋粟,圖片大小必須注意
allOut.copyTo(output);
// 關閉RenderScript對象靡菇,API>=23則使用rs.releaseAllContexts()
rs.destroy();
return output;
}
- 將bitmap轉為drawable并設置給view
/**
* 獲得背景的高斯模糊圖 drawable
*
* @param context
* @param radius
* @return
*/
public static Drawable getBackBlurDrawable(Context context, float radius) {
return new BitmapDrawable(context.getResources(), getBackBlurBitmap(context, radius));
}
View view = findViewById(R.id.layout_dialog);
view.setBackground(mBackDrawable);
這樣就對圖片做成了高斯模糊.
動態(tài)設置背景
我寫的demo是監(jiān)聽menu鍵去彈出dialog,在處理邏輯的時候發(fā)現截圖不變.原來寫的截圖邏輯是:
/**
* 獲取整個窗口的截圖
*
* @param context
* @return
*/
@SuppressLint("NewApi")
private static Bitmap captureScreen(Activity context) {
View view = context.getWindow().getDecorView();
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
Bitmap bmp = view.getDrawingCache();
if (bmp == null) {
return null;
}
bmp.setHasAlpha(false);
bmp.prepareToDraw();
return bmp;
}
后來通過查閱資料發(fā)現這里需要把上一個view銷毀調才可以,添加以下的代碼:
if (view != null){
//清空緩沖
view.destroyDrawingCache();
}
這樣的話就實現了動態(tài)的功能,在多個界面設置高斯模糊.
代碼已經上傳到github上了CustomTvRecyclerView.
這篇文章介紹了為view動態(tài)設置高斯模糊的背景,希望對你有幫助.