高斯模糊(Gaussian blur)和毛玻璃效果(亦稱磨砂效果)帐偎,近兩年在移動端的UI設(shè)計上越來越流行蔗牡,特別是iOS手機(jī)上出現(xiàn)的較多痘煤,iOS系統(tǒng)也提供了相應(yīng)的API幫助開發(fā)人員分分鐘實現(xiàn)這兩個效果拨与。而Android系統(tǒng)則經(jīng)歷了一個漫長的探索過程哩治,對圖片的處理秃踩,從Java算法到NDK方式實現(xiàn)等,各種摸索層出不窮业筏。
值得欣慰的是憔杨,Google終于在API 11中引入了RenderScript,一個強(qiáng)大的圖片處理框架蒜胖,幫助Android開發(fā)人員專注于圖片處理算法而不是API的調(diào)度工作消别。使用RenderScript進(jìn)行圖片處理,還需要了解RenderScript Intrinsics台谢,一些可以幫助RenderScript快速實現(xiàn)各種圖片處理的操作類寻狂。比如ScriptIntrinsicBlur,可以簡單高效地幫助我們實現(xiàn)高斯模糊效果:
public Bitmap blurBitmap(Bitmap bitmap){
//Let's create an empty bitmap with the same size of the bitmap we want to blur
Bitmap outBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Config.ARGB_8888);
//Instantiate a new Renderscript
RenderScript rs = RenderScript.create(getApplicationContext());
//Create an Intrinsic Blur Script using the Renderscript
ScriptIntrinsicBlur blurScript = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));
//Create the Allocations (in/out) with the Renderscript and the in/out bitmaps
Allocation allIn = Allocation.createFromBitmap(rs, bitmap);
Allocation allOut = Allocation.createFromBitmap(rs, outBitmap);
//Set the radius of the blur: 0 < radius <= 25
blurScript.setRadius(25.0f);
//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;
}
通過設(shè)置模糊半徑(radius)的大小來控制圖片的清晰度朋沮,簡短的幾行代碼輕松實現(xiàn)圖片的高斯模糊處理蛇券,我們看一下radius等于最大值25時的圖片模糊效果:
原圖效果:
高斯模糊:
注意:ScriptIntrinsicBlur的相關(guān)方法只支持API 17及以上版本的系統(tǒng),為了兼容舊版本,Google供了support.v8包纠亚,在使用RenderScript和Intrinsics類時塘慕,引入v8包中的相關(guān)類即可:
import android.support.v8.renderscript.Allocation;
import android.support.v8.renderscript.Element;
import android.support.v8.renderscript.RenderScript;
import android.support.v8.renderscript.ScriptIntrinsicBlur;
同時,在app/build.gradle
文件的defaultConfig
配置中菜枷,添加如下兩行內(nèi)容即可:
defaultConfig {
......
renderscriptTargetApi 19
renderscriptSupportModeEnabled true
}
在設(shè)計上巧妙地運(yùn)用高斯模糊往往能達(dá)到出乎意料的體驗效果苍糠,比如大神daimajia就利用RenderScript和NineOldAndroids做了一個比較有創(chuàng)意的UI交互,開源庫為:AndroidViewHover啤誊,效果如下岳瞭,感興趣的同學(xué)可以一探究竟:
關(guān)于Android平臺的圖片模糊處理,在GitHub上有一些較為優(yōu)秀的開源類庫蚊锹,筆者整理了一些瞳筏,推薦給大家學(xué)習(xí)使用: