在市面上很多的APP都使用了對圖片作模糊化處理后作為背景的效果,來使得整個頁面更具有整體感。如下就是網易云音樂的音樂播放頁面:

很明顯這個頁面的背景是由中間的小圖片模糊化后而來的。最常用的模糊化處理就是高斯模糊。
高斯模糊的幾種實現方式:
(1)RenderScript
RenderScript是Google在Android 3.0(API 11)中引入的一個高性能圖片處理框架。
使用RenderScriprt實現高斯模糊:
首先在在build.gradle的defaultConfig中添加RenderScript的使用配置
renderscriptTargetApi 24
renderscriptSupportModeEnabled true
renderscriptTargetApi :
指定要生成的字節碼版本。我們(Goole官方)建議您將此值設置為最低API級別能夠提供所有的功能,你使用和設置renderscriptSupportModeEnabled為true。此設置的有效值是從11到
最近發布的API級別的任何整數值。
renderscriptSupportModeEnabled:
指定生成的字節碼應該回落到一個兼容的版本,如果運行的設備不支持目標版本。
下面就是使用RenderScriprt實現高斯模糊的方法:
public static Bitmap blurBitmap(Context context, Bitmap bitmap) { //用需要創建高斯模糊bitmap創建一個空的bitmapBitmap outBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888); // 初始化Renderscript,該類提供了RenderScript context,創建其他RS類之前必須先創建這個類,其控制RenderScript的初始化,資源管理及釋放 RenderScript rs = RenderScript.create(context); // 創建高斯模糊對象 ScriptIntrinsicBlur blurScript = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs)); // 創建Allocations,此類是將數據傳遞給RenderScript內核的主要方 法,并制定一個后備類型存儲給定類型 Allocation allIn = Allocation.createFromBitmap(rs, bitmap); Allocation allOut = Allocation.createFromBitmap(rs, outBitmap); //設定模糊度(注:Radius最大只能設置25.f) blurScript.setRadius(15.f); // Perform the Renderscript blurScript.setInput(allIn); blurScript.forEach(allOut); // Copy the final bitmap created by the out Allocation to the outBitmap allOut.copyTo(outBitmap); // recycle the original bitmap // bitmap.recycle(); // After finishing everything, we destroy the Renderscript. rs.destroy(); return outBitmap; }(2)Glide實現高斯模糊
Glide是一個比較強大也是比較常用的一個圖片加載庫,Glide中的Transformations用于在圖片顯示前對圖片進行處理。glide-transformations 這個庫為Glide提供了多種多樣的 Transformations實
現,其中就包括高斯模糊的實現BlurTransformation
compile 'com.github.bumptech.glide:glide:3.7.0'compile 'jp.wasabeef:glide-transformations:2.0.1'
通過這兩個庫的結合使用,就可以使用其中的BlurTransformation實現圖片的高斯模糊
Glide.with(context).load(R.drawable.defalut_photo).bitmapTransform(new BlurTransformation(context, radius)).into(mImageView);
其中radius的取值范圍是1-25,radius越大,模糊度越高。
以上所述是小編個大家介紹的Android實現圖片的高斯模糊,希望對大家有所幫助,如果大家有任何疑問歡迎給我留言,小編會及時回復大家的!
新聞熱點
疑難解答