Android RenderScript 簡單高效實現圖片的高斯模糊效果

crljjohzyv 8年前發布 | 38K 次閱讀 Android開發 移動開發 RenderScript

高斯模糊(Gaussian blur)和毛玻璃效果(亦稱磨砂效果),近兩年在移動端的UI設計上越來越流行,特別是iOS手機上出現的較多,iOS系統也提供了相應的API幫助開發人員分分鐘實現這兩個效果。而Android系統則經歷了一個漫長的探索過程,對圖片的處理,從Java算法到NDK方式實現等,各種摸索層出不窮。

值得欣慰的是,Google終于在API 11中引入了 RenderScript ,一個強大的圖片處理框架,幫助Android開發人員專注于圖片處理算法而不是API的調度工作。使用RenderScript進行圖片處理,還需要了解 RenderScript Intrinsics ,一些可以幫助RenderScript快速實現各種圖片處理的操作類。比如 ScriptIntrinsicBlur ,可以簡單高效地幫助我們實現高斯模糊效果:

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;   

}

通過設置模糊半徑(radius)的大小來控制圖片的清晰度,簡短的幾行代碼輕松實現圖片的高斯模糊處理,我們看一下radius等于最大值25時的圖片模糊效果:

原圖效果:

高斯模糊:

注意:ScriptIntrinsicBlur的相關方法只支持API 17及以上版本的系統,為了兼容舊版本,Google供了support.v8包,在使用RenderScript和Intrinsics類時,引入v8包中的相關類即可:

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 配置中,添加如下兩行內容即可:

defaultConfig {
    ......
    renderscriptTargetApi 19
    renderscriptSupportModeEnabled  true
}

在設計上巧妙地運用高斯模糊往往能達到出乎意料的體驗效果,比如大神 daimajia 就利用RenderScript和 NineOldAndroids 做了一個比較有創意的UI交互,開源庫為: AndroidViewHover ,效果如下,感興趣的同學可以一探究竟:

 

 

來自:http://yifeng.studio/2016/10/20/android-renderscript-blur/

 

 本文由用戶 crljjohzyv 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!