目录(?)[-]

  1. 高斯模糊实现方案探究
    1. RenderScript
    2. FastBlur
    3. AdvancedFastBlur
    4. Warning

高斯模糊实现方案探究

现在越来越多的app在背景图中使用高斯模糊效果,如yahoo天气,效果做得很炫。 这里就用一个demo来谈谈它的不同实现方式及各自的优缺点。

1. RenderScript

谈到高斯模糊,第一个想到的就是RenderScript。RenderScript是由Android3.0引入,用来在Android上编写高性能代码的一种语言(使用C99标准)。 引用官方文档的描述:

RenderScript runtime will parallelize work across all processors available on a device, such as multi-core CPUs, GPUs, or DSPs, allowing you to focus on expressing algorithms rather than scheduling work or load balancing.

为了在Android中使用RenderScript,我们需要(直接贴官方文档,比直译更通俗易懂):

  • High-performance compute kernels are written in a C99-derived language.
  • A Java API is used for managing the lifetime of RenderScript resources and controlling kernel execution.

学习文档:http://developer.android.com/guide/topics/renderscript/compute.html

上面两点总结成一句话为:我们需要一组compute kernels(.rs文件中编写),及一组用于控制renderScript相关的java api(.rs文件自动生成为java类)。 由于compute kernels的编写需要一定的学习成本,从JELLY_BEAN_MR1开始,Androied内置了一些compute kernels用于常用的操作,其中就包括了Gaussian blur

下面,通过实操来讲解一下RenderScript来实现高斯模糊,最终实现效果(讲文字背景进行模糊处理):

布局:

[html] view plain copy
  1. <?xmlversion="1.0"encoding="utf-8"?>
  2. <FrameLayoutxmlns:android="http://schemas.android.com/apk/res/android"
  3. android:layout_width="match_parent"
  4. android:layout_height="match_parent">
  5. <ImageView
  6. android:id="@+id/picture"
  7. android:layout_width="match_parent"
  8. android:layout_height="match_parent"
  9. android:src="@drawable/splash"
  10. android:scaleType="centerCrop"/>
  11. <TextView
  12. android:id="@+id/text"
  13. android:gravity="center_horizontal"
  14. android:layout_width="match_parent"
  15. android:layout_height="wrap_content"
  16. android:text="GaussianBlur"
  17. android:textColor="@android:color/black"
  18. android:layout_gravity="center_vertical"
  19. android:textStyle="bold"
  20. android:textSize="48sp"/>
  21. <LinearLayout
  22. android:id="@+id/controls"
  23. android:layout_width="match_parent"
  24. android:layout_height="wrap_content"
  25. android:background="#7f000000"
  26. android:orientation="vertical"
  27. android:layout_gravity="bottom"/>
  28. </FrameLayout>

核心代码:

[java] view plain copy
  1. privatevoidapplyBlur(){
  2. image.getViewTreeObserver().addOnPreDrawListener(newViewTreeObserver.OnPreDrawListener(){
  3. @Override
  4. publicbooleanonPreDraw(){
  5. image.getViewTreeObserver().removeOnPreDrawListener(this);
  6. image.buildDrawingCache();
  7. Bitmapbmp=image.getDrawingCache();
  8. blur(bmp,text,true);
  9. returntrue;
  10. }
  11. });
  12. }
  13. @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
  14. privatevoidblur(Bitmapbkg,Viewview){
  15. longstartMs=System.currentTimeMillis();
  16. floatradius=20;
  17. Bitmapoverlay=Bitmap.createBitmap((int)(view.getMeasuredWidth()),(int)(view.getMeasuredHeight()),Bitmap.Config.ARGB_8888);
  18. Canvascanvas=newCanvas(overlay);
  19. canvas.translate(-view.getLeft(),-view.getTop());
  20. canvas.drawBitmap(bkg,0,0,null);
  21. RenderScriptrs=RenderScript.create(SecondActivity.this);
  22. AllocationoverlayAlloc=Allocation.createFromBitmap(rs,overlay);
  23. ScriptIntrinsicBlurblur=ScriptIntrinsicBlur.create(rs,overlayAlloc.getElement());
  24. blur.setInput(overlayAlloc);
  25. blur.setRadius(radius);
  26. blur.forEach(overlayAlloc);
  27. overlayAlloc.copyTo(overlay);
  28. view.setBackground(newBitmapDrawable(getResources(),overlay));
  29. rs.destroy();
  30. statusText.setText("cost"+(System.currentTimeMillis()-startMs)+"ms");
  31. }

当ImageView开始加载背景图时,取出它的drawableCache,进行blur处理,Gaussian blur的主要逻辑在blur函数中。对于在Java中使用RenderScript,文档中也有详细描述,对应到我们的代码,步骤为:

  • 初始化一个RenderScript Context.
  • 至少创建一个Allocation对象用于存储需要处理的数据.
  • 创建compute kernel的实例,本例中是内置的ScriptIntrinsicBlur对象.
  • 设置ScriptIntrinsicBlur实例的相关属性,包括Allocation, radius等.
  • 开始blur操作,对应(forEach).
  • 将blur后的结果拷贝回bitmap中。

此时,我们便得到了一个经过高斯模糊的bitmap。

从上图可以看到,模糊处理花费了38ms(测试机为小米2s),由于Android假设每一帧的处理时间不能超过16ms(屏幕刷新频率60fps),因此,若在主线程里执行RenderScript操作,可能会造成卡顿现象。最好的方式是将其放入AsyncTask中执行。

此外,RenderScript在3.0引入,而一些内置的compute kernelJELLY_BEAN_MR1中引入,为了在低版本手机中使用这些特性,我们不得不引入renderscript_v8兼容包,对于手Q安装包增量的硬性指标,貌似只能放弃JELLY_BEAN_MR1以下的用户?

有点不甘心,想想别的解决方案吧。

2. FastBlur

由于高斯模糊归根结底是像素点的操作,也许在java层可以直接操作像素点来进行模糊化处理。google一下,果不其然,一个名为stackblur的开源项目提供了名为fastBlur的方法在java层直接进行高斯模糊处理。

项目地址请猛戳: stackblur

ok,现在来改造我们的程序.

[java] view plain copy
  1. privatevoidblur(Bitmapbkg,Viewview){
  2. longstartMs=System.currentTimeMillis();
  3. floatradius=20;
  4. Bitmapoverlay=Bitmap.createBitmap((int)(view.getMeasuredWidth()),(int)(view.getMeasuredHeight()),Bitmap.Config.ARGB_8888);
  5. Canvascanvas=newCanvas(overlay);
  6. canvas.translate(-view.getLeft(),-view.getTop());
  7. canvas.drawBitmap(bkg,0,0,null);
  8. overlay=FastBlur.doBlur(overlay,(int)radius,true);
  9. view.setBackground(newBitmapDrawable(getResources(),overlay));
  10. statusText.setText("cost"+(System.currentTimeMillis()-startMs)+"ms");
  11. }

这里,仅仅是把RenderScript相关的操作换成了FastBlur提供的api。效果图如下:

效果还不错,与RenderScript的实现差不多,但花费的时间却整整多了2倍多,这完全是无法接受的。好吧,只能继续探究。

3. AdvancedFastBlur

stackOverflow对于程序员来说永远是最大的宝藏。http://stackoverflow.com/questions/2067955/fast-bitmap-blur-for-android-sdk这篇提问帖终于提供了新的解决思路:

This is a shot in the dark, but you might try shrinking the image and then enlarging it again. This can be done with Bitmap.createScaledBitmap(Bitmap src, int dstWidth, int dstHeight, boolean filter). Make sure and set the filter parameter to true. It'll run in native code so it might be faster.

它所表述的原理为先通过缩小图片,使其丢失一些像素点,接着进行模糊化处理,然后再放大到原来尺寸。由于图片缩小后再进行模糊处理,需要处理的像素点和半径都变小,从而使得模糊处理速度加快。 了解原理,继续改善:

[java] view plain copy
  1. privatevoidblur(Bitmapbkg,Viewview){
  2. longstartMs=System.currentTimeMillis();
  3. floatradius=2;
  4. floatscaleFactor=8;
  5. Bitmapoverlay=Bitmap.createBitmap((int)(view.getMeasuredWidth()/scaleFactor),(int)(view.getMeasuredHeight()/scaleFactor),Bitmap.Config.ARGB_8888);
  6. Canvascanvas=newCanvas(overlay);
  7. canvas.translate(-view.getLeft()/scaleFactor,-view.getTop()/scaleFactor);
  8. canvas.scale(1/scaleFactor,1/scaleFactor);
  9. Paintpaint=newPaint();
  10. paint.setFlags(Paint.FILTER_BITMAP_FLAG);
  11. canvas.drawBitmap(bkg,0,0,paint);
  12. overlay=FastBlur.doBlur(overlay,(int)radius,true);
  13. view.setBackground(newBitmapDrawable(getResources(),overlay));
  14. statusText.setText("cost"+(System.currentTimeMillis()-startMs)+"ms");
  15. }

最新的代码所创建的bitmap为原图的1/8大小,接着,同样使用fastBlur来进行模糊化处理,最后再为textview设置背景,此时,背景图会自动放大到初始大小。注意,由于这里进行了缩放,radius的取值也要比之前小得多(这里将原始取值除以8得到近似值2)。下面是效果图:

惊呆了有木有!!效果一样,处理速度却快得惊人。它相对于renderScript方案来说,节省了拷贝bitmap到Allocation中,处理完后再拷贝回来的时间开销。

4. Warning

由于FastBlur是将整个bitmap拷贝到一个临时的buffer中进行像素点操作,因此,它不适合处理一些过大的背景图(很容导致OOM有木有~)。对于开发者来说,RenderScript方案和FastBlur方案的选择,需要你根据具体业务来衡量!

更多相关文章

  1. Android(安卓)- LayoutAnimation 动画效果 - 示例
  2. Android——ContentProvider总结
  3. Android仿考拉全局滑动返回及联动效果的实现方法
  4. Android(安卓)OpenGLES2.0(十七)——球形天空盒VR效果实现
  5. 实现ListView的条目下自动隐藏显示的布局
  6. 国产神器天语Android双核手机W700线下赏机经历
  7. Android的px、dp和sp等单位的区别详解
  8. Android材料设计兼容函数库(Design Support Library)(II)浮动操作按
  9. Android图像处理技术(实现Android中的PS)(三)

随机推荐

  1. jquery 半透明遮罩效果 小结
  2. 将ISO-8859-1转换为UTF-8 [重复]
  3. jQueryValidate的js效果出不来需要注意的
  4. 如何检测“:”之前的单词并使用jquery进
  5. 当使用Javascript选择其中一个时,如何禁用
  6. 用Jquery控制元素的上下移动 实现排序功
  7. 输入-文本对齐:用jQuery右填充输入
  8. jquery根据class来选取对应的(共150分啊)
  9. jquery 监控文本框键盘事件(回车事件),附常
  10. 使用javascript进行内容占位符问题的第二