搜集很多关于背景虚化的帖子, @IcyFox 的见解 : 模糊实现方案探究
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来实现高斯模糊,最终实现效果(讲文字背景进行模糊处理):
布局:
- <?xml version="1.0" encoding="utf-8"?>
- <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent" >
- <ImageView
- android:id="@+id/picture"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:src="@drawable/splash"
- android:scaleType="centerCrop" />
- <TextView
- android:id="@+id/text"
- android:gravity="center_horizontal"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:text="Gaussian Blur"
- android:textColor="@android:color/black"
- android:layout_gravity="center_vertical"
- android:textStyle="bold"
- android:textSize="48sp" />
- <LinearLayout
- android:id="@+id/controls"
- android:layout_width="match_parent"