上圖展示了一種很典型的視覺(jué)效果——文字的背景不再是固定的盖奈,而是將底層的相應(yīng)區(qū)域模糊化芽丹,好似蓋了一層毛玻璃。
其原理也很簡(jiǎn)單卜朗,分為三步走:
- 獲取底層的view的Bitmap——b1
- 將b1模糊化拔第,保存為b2
- 把b2設(shè)為文字的背景。
里面涉及到的技術(shù)點(diǎn)有兩個(gè):
- 何時(shí)訪問(wèn)能獲取到底層view的完整Bitmap场钉?
- 如何模糊化蚊俺,該采用什么算法?
技術(shù)點(diǎn)一:何時(shí)訪問(wèn)能獲取到底層view的完整Bitmap逛万?
ViewTreeObserver里面有一個(gè)監(jiān)聽(tīng)器為OnPreDrawListener
// 當(dāng)一個(gè)視圖樹(shù)將要繪制時(shí)泳猬,所要調(diào)用的回調(diào)函數(shù)的接口類
public interface OnPreDrawListener {
boolean onPreDraw();
}
當(dāng)它執(zhí)行時(shí),布局文件經(jīng)過(guò)了measured宇植、laid out得封、displayed,即將被繪制到屏幕指郁,此時(shí)調(diào)用它的getDrawingCache()
方法可以獲得其Bitmap忙上。完整方法如下:
lowerView.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
@Override
public boolean onPreDraw() {
lowerView.getViewTreeObserver().removeOnPreDrawListener(this);
lowerView.buildDrawingCache();
Bitmap bmp = lowerView.getDrawingCache();
return true;
}
});
技術(shù)點(diǎn)二:如何模糊化,該采用什么算法闲坎?
方案有兩種:
- 借助Renderscript做高斯模糊疫粥,本質(zhì)上是做卷積計(jì)算茬斧。
- 采用StackBlur算法對(duì)圖片進(jìn)行模糊處理,相較于高斯模糊梗逮,計(jì)算量小了很多项秉。
兩種方案都可以進(jìn)行對(duì)Bitmap對(duì)象的模糊處理,但當(dāng)模糊半徑增大時(shí)慷彤,StackBlur能夠保持較好的性能娄蔼,且不受Renderscript半徑25px的限制。
在GitHub項(xiàng)目有一個(gè)項(xiàng)目blurring底哗,其實(shí)現(xiàn)了StackBlur算法的Java實(shí)現(xiàn)版FastBlur贷屎,并給出兩種方案效率對(duì)比demo。經(jīng)過(guò)測(cè)試艘虎,
- 在Mac上Genymotion模擬器下運(yùn)行Android4.4.4,Renderscript耗時(shí)42ms咒吐,F(xiàn)astBlur耗時(shí)82ms
- 在小米4真機(jī)上運(yùn)行Android6.0.1野建,Renderscript耗時(shí)124ms,F(xiàn)astBlur耗時(shí)271ms
看起來(lái)恬叹,Renderscript的性能更好候生,應(yīng)該是Android上對(duì)Renderscript做了優(yōu)化。盡管如此绽昼,考慮到Android中渲染一幀的時(shí)間應(yīng)該不超過(guò)16ms(60fps)唯鸭,這樣的性能并不友好。blurring作者想出了另外一種思路:
把bitmap的尺寸先降低然后進(jìn)行模糊處理硅确,然后再放大尺寸
這時(shí)候目溉,效率提升非常明顯:
- 在Mac上Genymotion模擬器下運(yùn)行Android4.4.4,Renderscript耗時(shí)5ms菱农,F(xiàn)astBlur耗時(shí)1ms
- 在小米4真機(jī)上運(yùn)行Android6.0.1缭付,Renderscript耗時(shí)16ms,F(xiàn)astBlur耗時(shí)7ms循未。
生成的模糊圖片當(dāng)然有所不同陷猫,但是都是模糊背景,所以對(duì)用戶而言沒(méi)有太大差別的妖。
好了绣檬,至此Android上制作毛玻璃背景模糊效果的技術(shù)都確定了。
源碼
我在blurring基礎(chǔ)上做了封裝嫂粟,接口如下:
/**
*
* @param context 上下文
* @param lowerView 底層view控件
* @param upperView 需要模糊背景的控件
*/
public static void doBlur(final Context context, final View lowerView, final View upperView) {
lowerView.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
@Override
public boolean onPreDraw() {
lowerView.getViewTreeObserver().removeOnPreDrawListener(this);
lowerView.buildDrawingCache();
Bitmap bmp = lowerView.getDrawingCache();
doBlur(context, bmp, upperView, true);
return true;
}
});
}
相對(duì)應(yīng)類有兩個(gè):
- RSBlur
package com.paveldudka.util;
import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.renderscript.Allocation;
import android.renderscript.RenderScript;
import android.renderscript.ScriptIntrinsicBlur;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.view.ViewTreeObserver;
/**
* Created by shitianci on 16/8/8.
*/
public class RSBlur {
/**
*
* @param context 上下文
* @param lowerView 底層view控件
* @param upperView 需要模糊背景的控件
*/
public static void doBlur(final Context context, final View lowerView, final View upperView) {
lowerView.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
@Override
public boolean onPreDraw() {
lowerView.getViewTreeObserver().removeOnPreDrawListener(this);
lowerView.buildDrawingCache();
Bitmap bmp = lowerView.getDrawingCache();
doBlur(context, bmp, upperView, true);
return true;
}
});
}
/**
*
* @param context 上下文
* @param bkg 原圖
* @param view 需要模糊背景的控件
* @param isDownScale 是否降低等級(jí)娇未,優(yōu)化效率(建議開(kāi)啟)
*/
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
public static void doBlur(Context context, Bitmap bkg, View view, boolean isDownScale) {
float scaleFactor = 1;
float radius = 20;
if (isDownScale) {
scaleFactor = 8;
radius = 2;
}
Bitmap overlay = Bitmap.createBitmap((int) (view.getMeasuredWidth() / scaleFactor),
(int) (view.getMeasuredHeight() / scaleFactor), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(overlay);
canvas.translate(-view.getLeft() / scaleFactor, -view.getTop() / scaleFactor);
canvas.scale(1 / scaleFactor, 1 / scaleFactor);
Paint paint = new Paint();
paint.setFlags(Paint.FILTER_BITMAP_FLAG);
canvas.drawBitmap(bkg, 0, 0, paint);
RenderScript rs = RenderScript.create(context);
Allocation overlayAlloc = Allocation.createFromBitmap(
rs, overlay);
ScriptIntrinsicBlur blur = ScriptIntrinsicBlur.create(
rs, overlayAlloc.getElement());
blur.setInput(overlayAlloc);
blur.setRadius(radius);
blur.forEach(overlayAlloc);
overlayAlloc.copyTo(overlay);
view.setBackground(new BitmapDrawable(context.getResources(), overlay));
rs.destroy();
}
}
- FastBlur
package com.paveldudka.util;
import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.view.View;
import android.view.ViewTreeObserver;
/**
* Created by paveld on 3/6/14.
*/
public class FastBlur {
/**
*
* @param context 上下文
* @param lowerView 底層view控件
* @param upperView 需要模糊背景的控件
*/
public static void doBlur(final Context context, final View lowerView, final View upperView) {
lowerView.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
@Override
public boolean onPreDraw() {
lowerView.getViewTreeObserver().removeOnPreDrawListener(this);
lowerView.buildDrawingCache();
Bitmap bmp = lowerView.getDrawingCache();
doBlur(context, bmp, upperView, true);
return true;
}
});
}
/**
*
* @param context 上下文
* @param bkg 原圖
* @param view 需要模糊背景的控件
* @param isDownScale 是否降低等級(jí),優(yōu)化效率(建議開(kāi)啟)
*/
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public static void doBlur(Context context, Bitmap bkg, View view, boolean isDownScale) {
float scaleFactor = 1;
float radius = 20;
if (isDownScale) {
scaleFactor = 8; //bitmap的尺寸縮小到原圖的1/8
radius = 2;
}
Bitmap overlay = Bitmap.createBitmap((int) (view.getMeasuredWidth()/scaleFactor),
(int) (view.getMeasuredHeight()/scaleFactor), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(overlay);
canvas.translate(-view.getLeft()/scaleFactor, -view.getTop()/scaleFactor);
canvas.scale(1 / scaleFactor, 1 / scaleFactor);
Paint paint = new Paint();
paint.setFlags(Paint.FILTER_BITMAP_FLAG);
canvas.drawBitmap(bkg, 0, 0, paint);
overlay = FastBlur.doBlur(overlay, (int)radius, true);
view.setBackground(new BitmapDrawable(context.getResources(), overlay));
}
public static Bitmap doBlur(Bitmap sentBitmap, int radius, boolean canReuseInBitmap) {
// Stack Blur v1.0 from
// http://www.quasimondo.com/StackBlurForCanvas/StackBlurDemo.html
//
// Java Author: Mario Klingemann <mario at quasimondo.com>
// http://incubator.quasimondo.com
// created Feburary 29, 2004
// Android port : Yahel Bouaziz <yahel at kayenko.com>
// http://www.kayenko.com
// ported april 5th, 2012
// This is a compromise between Gaussian Blur and Box blur
// It creates much better looking blurs than Box Blur, but is
// 7x faster than my Gaussian Blur implementation.
//
// I called it Stack Blur because this describes best how this
// filter works internally: it creates a kind of moving stack
// of colors whilst scanning through the lowerView. Thereby it
// just has to add one new block of color to the right side
// of the stack and remove the leftmost color. The remaining
// colors on the topmost layer of the stack are either added on
// or reduced by one, depending on if they are on the right or
// on the left side of the stack.
//
// If you are using this algorithm in your code please add
// the following line:
//
// Stack Blur Algorithm by Mario Klingemann <mario@quasimondo.com>
Bitmap bitmap;
if (canReuseInBitmap) {
bitmap = sentBitmap;
} else {
bitmap = sentBitmap.copy(sentBitmap.getConfig(), true);
}
if (radius < 1) {
return (null);
}
int w = bitmap.getWidth();
int h = bitmap.getHeight();
int[] pix = new int[w * h];
bitmap.getPixels(pix, 0, w, 0, 0, w, h);
int wm = w - 1;
int hm = h - 1;
int wh = w * h;
int div = radius + radius + 1;
int r[] = new int[wh];
int g[] = new int[wh];
int b[] = new int[wh];
int rsum, gsum, bsum, x, y, i, p, yp, yi, yw;
int vmin[] = new int[Math.max(w, h)];
int divsum = (div + 1) >> 1;
divsum *= divsum;
int dv[] = new int[256 * divsum];
for (i = 0; i < 256 * divsum; i++) {
dv[i] = (i / divsum);
}
yw = yi = 0;
int[][] stack = new int[div][3];
int stackpointer;
int stackstart;
int[] sir;
int rbs;
int r1 = radius + 1;
int routsum, goutsum, boutsum;
int rinsum, ginsum, binsum;
for (y = 0; y < h; y++) {
rinsum = ginsum = binsum = routsum = goutsum = boutsum = rsum = gsum = bsum = 0;
for (i = -radius; i <= radius; i++) {
p = pix[yi + Math.min(wm, Math.max(i, 0))];
sir = stack[i + radius];
sir[0] = (p & 0xff0000) >> 16;
sir[1] = (p & 0x00ff00) >> 8;
sir[2] = (p & 0x0000ff);
rbs = r1 - Math.abs(i);
rsum += sir[0] * rbs;
gsum += sir[1] * rbs;
bsum += sir[2] * rbs;
if (i > 0) {
rinsum += sir[0];
ginsum += sir[1];
binsum += sir[2];
} else {
routsum += sir[0];
goutsum += sir[1];
boutsum += sir[2];
}
}
stackpointer = radius;
for (x = 0; x < w; x++) {
r[yi] = dv[rsum];
g[yi] = dv[gsum];
b[yi] = dv[bsum];
rsum -= routsum;
gsum -= goutsum;
bsum -= boutsum;
stackstart = stackpointer - radius + div;
sir = stack[stackstart % div];
routsum -= sir[0];
goutsum -= sir[1];
boutsum -= sir[2];
if (y == 0) {
vmin[x] = Math.min(x + radius + 1, wm);
}
p = pix[yw + vmin[x]];
sir[0] = (p & 0xff0000) >> 16;
sir[1] = (p & 0x00ff00) >> 8;
sir[2] = (p & 0x0000ff);
rinsum += sir[0];
ginsum += sir[1];
binsum += sir[2];
rsum += rinsum;
gsum += ginsum;
bsum += binsum;
stackpointer = (stackpointer + 1) % div;
sir = stack[(stackpointer) % div];
routsum += sir[0];
goutsum += sir[1];
boutsum += sir[2];
rinsum -= sir[0];
ginsum -= sir[1];
binsum -= sir[2];
yi++;
}
yw += w;
}
for (x = 0; x < w; x++) {
rinsum = ginsum = binsum = routsum = goutsum = boutsum = rsum = gsum = bsum = 0;
yp = -radius * w;
for (i = -radius; i <= radius; i++) {
yi = Math.max(0, yp) + x;
sir = stack[i + radius];
sir[0] = r[yi];
sir[1] = g[yi];
sir[2] = b[yi];
rbs = r1 - Math.abs(i);
rsum += r[yi] * rbs;
gsum += g[yi] * rbs;
bsum += b[yi] * rbs;
if (i > 0) {
rinsum += sir[0];
ginsum += sir[1];
binsum += sir[2];
} else {
routsum += sir[0];
goutsum += sir[1];
boutsum += sir[2];
}
if (i < hm) {
yp += w;
}
}
yi = x;
stackpointer = radius;
for (y = 0; y < h; y++) {
// Preserve alpha channel: ( 0xff000000 & pix[yi] )
pix[yi] = (0xff000000 & pix[yi]) | (dv[rsum] << 16) | (dv[gsum] << 8) | dv[bsum];
rsum -= routsum;
gsum -= goutsum;
bsum -= boutsum;
stackstart = stackpointer - radius + div;
sir = stack[stackstart % div];
routsum -= sir[0];
goutsum -= sir[1];
boutsum -= sir[2];
if (x == 0) {
vmin[y] = Math.min(y + r1, hm) * w;
}
p = x + vmin[y];
sir[0] = r[p];
sir[1] = g[p];
sir[2] = b[p];
rinsum += sir[0];
ginsum += sir[1];
binsum += sir[2];
rsum += rinsum;
gsum += ginsum;
bsum += binsum;
stackpointer = (stackpointer + 1) % div;
sir = stack[stackpointer];
routsum += sir[0];
goutsum += sir[1];
boutsum += sir[2];
rinsum -= sir[0];
ginsum -= sir[1];
binsum -= sir[2];
yi += w;
}
}
bitmap.setPixels(pix, 0, w, 0, 0, w, h);
return (bitmap);
}
}