[译]Android高级技巧: Renderscript优化模糊效果

来源:互联网 发布:物业软件 编辑:程序博客网 时间:2024/05/20 04:26

Android ProTips: Blur Images Efficiently using Renderscript
Blurring images like a feather on Android

很多开发者都需要实现模糊效果,它可能需要一些时间和精力才能实现。而且,因为需要大量的图片处理,如果没写好代码,CPU和内存将会产生很大的负担。

这有一个快速有效的方法处理模糊图片,就是使用Renderscript。
从API11(蜜罐)起,Renderscript允许使用GPU加速,来处理高性能3D渲染和计算处理。
Renderscript是一个十分复的杂铰接性产品,允许进行深度定制并使用C99语言编码,这使得它具有移植性,高性能和易用性。

然而,从API17(4.2.2)起,Renderscript提供了一些内置函数来执行明确定义的操作,称为内部函数。
内部函数是预定义脚本,它允许执行模糊,混纺,矩阵卷积及更多的效果处理,而不需要写Renderscript代码。
简单的方法来可以轻松的处理Bitmap的模糊过滤效果:

public Bitmap blurBitmap(Bitmap bitmap){//Let’s create an empty bitmap with the same size of the bitmap we want to blurBitmap 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 in/out Allocations 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 blurScript.setRadius(25.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;}

还有……瞧!模糊的位图!:-)
请记住,运行前面的代码需要的最低API17(4.2.2)版本。

下面是此方法的要点是:
https://gist.github.com/Mariuxtheone/903c35b4927c0df18cf8

如果你想发现更多的内部函数,请看Android开发者博客的这篇博文:
http://android-developers.blogspot.it/2013/08/renderscript-intrinsics.html

如果你想深入了解Renderscript,请查看这些链接:
http://android-developers.blogspot.it/2011/02/introducing-renderscript.html
http://android-developers.blogspot.it/2011/03/renderscript.html

0 0
原创粉丝点击