Android上如何做出毛玻璃模糊的效果?

上圖展示了一種很典型的視覺(jué)效果——文字的背景不再是固定的盖奈,而是將底層的相應(yīng)區(qū)域模糊化芽丹,好似蓋了一層毛玻璃。

其原理也很簡(jiǎn)單卜朗,分為三步走:

  1. 獲取底層的view的Bitmap——b1
  2. 將b1模糊化拔第,保存為b2
  3. 把b2設(shè)為文字的背景。

里面涉及到的技術(shù)點(diǎn)有兩個(gè):

  1. 何時(shí)訪問(wèn)能獲取到底層view的完整Bitmap场钉?
  2. 如何模糊化蚊俺,該采用什么算法?

技術(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)二:如何模糊化,該采用什么算法闲坎?

方案有兩種:

  1. 借助Renderscript做高斯模糊疫粥,本質(zhì)上是做卷積計(jì)算茬斧。
  2. 采用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è):

  1. 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();
    }
}
  1. 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);
    }
}

參考

  1. Android高級(jí)模糊技術(shù)
  2. GitHub項(xiàng)目·blurring
  3. 知乎問(wèn)題·Android 5.0 下毛玻璃(磨砂)效果如何實(shí)現(xiàn)星虹?
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末忘蟹,一起剝皮案震驚了整個(gè)濱河市飒房,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌媚值,老刑警劉巖狠毯,帶你破解...
    沈念sama閱讀 212,383評(píng)論 6 493
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異褥芒,居然都是意外死亡嚼松,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,522評(píng)論 3 385
  • 文/潘曉璐 我一進(jìn)店門锰扶,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)献酗,“玉大人,你說(shuō)我怎么就攤上這事坷牛『辟耍” “怎么了?”我有些...
    開(kāi)封第一講書人閱讀 157,852評(píng)論 0 348
  • 文/不壞的土叔 我叫張陵京闰,是天一觀的道長(zhǎng)颜及。 經(jīng)常有香客問(wèn)我,道長(zhǎng)蹂楣,這世上最難降的妖魔是什么俏站? 我笑而不...
    開(kāi)封第一講書人閱讀 56,621評(píng)論 1 284
  • 正文 為了忘掉前任,我火速辦了婚禮痊土,結(jié)果婚禮上肄扎,老公的妹妹穿的比我還像新娘。我一直安慰自己赁酝,他們只是感情好犯祠,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,741評(píng)論 6 386
  • 文/花漫 我一把揭開(kāi)白布。 她就那樣靜靜地躺著酌呆,像睡著了一般雷则。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上肪笋,一...
    開(kāi)封第一講書人閱讀 49,929評(píng)論 1 290
  • 那天月劈,我揣著相機(jī)與錄音,去河邊找鬼藤乙。 笑死猜揪,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的坛梁。 我是一名探鬼主播而姐,決...
    沈念sama閱讀 39,076評(píng)論 3 410
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼划咐!你這毒婦竟也來(lái)了拴念?” 一聲冷哼從身側(cè)響起钧萍,我...
    開(kāi)封第一講書人閱讀 37,803評(píng)論 0 268
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎政鼠,沒(méi)想到半個(gè)月后风瘦,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 44,265評(píng)論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡公般,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,582評(píng)論 2 327
  • 正文 我和宋清朗相戀三年万搔,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片官帘。...
    茶點(diǎn)故事閱讀 38,716評(píng)論 1 341
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡瞬雹,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出刽虹,到底是詐尸還是另有隱情酗捌,我是刑警寧澤,帶...
    沈念sama閱讀 34,395評(píng)論 4 333
  • 正文 年R本政府宣布涌哲,位于F島的核電站胖缤,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏膛虫。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 40,039評(píng)論 3 316
  • 文/蒙蒙 一钓猬、第九天 我趴在偏房一處隱蔽的房頂上張望稍刀。 院中可真熱鬧,春花似錦敞曹、人聲如沸账月。這莊子的主人今日做“春日...
    開(kāi)封第一講書人閱讀 30,798評(píng)論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)局齿。三九已至,卻和暖如春橄登,著一層夾襖步出監(jiān)牢的瞬間抓歼,已是汗流浹背。 一陣腳步聲響...
    開(kāi)封第一講書人閱讀 32,027評(píng)論 1 266
  • 我被黑心中介騙來(lái)泰國(guó)打工拢锹, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留谣妻,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 46,488評(píng)論 2 361
  • 正文 我出身青樓卒稳,卻偏偏與公主長(zhǎng)得像蹋半,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子充坑,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,612評(píng)論 2 350

推薦閱讀更多精彩內(nèi)容