Android實現圖片的高斯模糊(兩種方式)
原文地址:http://www.jb51.net/article/107482.htm
在市面上很多的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實現高斯模糊的方法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
public
static Bitmap blurBitmap(Context context, Bitmap bitmap) {
//用需要建立高斯模糊bitmap建立一個空的bitmap
Bitmap 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
1 2 |
compile 'com.github.bumptech.glide:glide:3.7.0'
compile 'jp.wasabeef:glide-transformations:2.0.1'
|
通過這兩個庫的結合使用,就可以使用其中的BlurTransformation實現圖片的高斯模糊
?1 |
Glide.with(context).load(R.drawable.defalut_photo).bitmapTransform( new
BlurTransformation(context, radius)).into(mImageView);
|
其中radius的取值範圍是1-25,radius越大,模糊度越高。