Android RenderScript 简单高效实现图片的高斯模糊效果

crljjohzyv 7年前
   <p>高斯模糊(Gaussian blur)和毛玻璃效果(亦称磨砂效果),近两年在移动端的UI设计上越来越流行,特别是iOS手机上出现的较多,iOS系统也提供了相应的API帮助开发人员分分钟实现这两个效果。而Android系统则经历了一个漫长的探索过程,对图片的处理,从Java算法到NDK方式实现等,各种摸索层出不穷。</p>    <p>值得欣慰的是,Google终于在API 11中引入了 RenderScript ,一个强大的图片处理框架,帮助Android开发人员专注于图片处理算法而不是API的调度工作。使用RenderScript进行图片处理,还需要了解 RenderScript Intrinsics ,一些可以帮助RenderScript快速实现各种图片处理的操作类。比如 ScriptIntrinsicBlur ,可以简单高效地帮助我们实现高斯模糊效果:</p>    <pre>  <code class="language-java">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;       }  </code></pre>    <p>通过设置模糊半径(radius)的大小来控制图片的清晰度,简短的几行代码轻松实现图片的高斯模糊处理,我们看一下radius等于最大值25时的图片模糊效果:</p>    <p>原图效果:</p>    <p style="text-align:center"><img src="https://simg.open-open.com/show/f2f3ab51b34e7758a6eb48766b2869ba.png"></p>    <p>高斯模糊:</p>    <p style="text-align:center"><img src="https://simg.open-open.com/show/16f10a61d029a7236efadbb18d2886af.png"></p>    <p style="text-align:center">注意:ScriptIntrinsicBlur的相关方法只支持API 17及以上版本的系统,为了兼容旧版本,Google供了support.v8包,在使用RenderScript和Intrinsics类时,引入v8包中的相关类即可:</p>    <pre>  <code class="language-java">import android.support.v8.renderscript.Allocation;  import android.support.v8.renderscript.Element;  import android.support.v8.renderscript.RenderScript;  import android.support.v8.renderscript.ScriptIntrinsicBlur;  </code></pre>    <p>同时,在 app/build.gradle 文件的 defaultConfig 配置中,添加如下两行内容即可:</p>    <pre>  <code class="language-java">defaultConfig {   ......   renderscriptTargetApi 19   renderscriptSupportModeEnabled  true  }  </code></pre>    <p>在设计上巧妙地运用高斯模糊往往能达到出乎意料的体验效果,比如大神 daimajia 就利用RenderScript和 NineOldAndroids 做了一个比较有创意的UI交互,开源库为: AndroidViewHover ,效果如下,感兴趣的同学可以一探究竟:</p>    <p style="text-align:center"><img src="https://simg.open-open.com/show/9d6cbec1095806ff4150c786b2396682.gif"></p>    <p> </p>    <p> </p>    <p>来自:http://yifeng.studio/2016/10/20/android-renderscript-blur/</p>    <p> </p>