Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 高斯模糊實作:RenderScript 模糊背景與 BlurView 懸浮層

編輯:關於 Android 程式設計

毛玻璃效果在 App 裡幾乎是標配。Android 上有兩條主流做法:一是用 RenderScript 把整張背景圖預先模糊,當作 View 的背景;二是用第三方 BlurView,讓模糊區域即時反映背後內容的變化。兩者用途不同,下面分別說明。

做法一:把圖片轉成模糊背景

public static void updateBgToBlur(Activity a, Bitmap bmpToBlur, View view, int resId) {
    // 先縮圖,降低後續計算量
    BitmapFactory.Options opt = new BitmapFactory.Options();
    opt.inJustDecodeBounds = true;
    opt.inSampleSize = 8;
    opt.inJustDecodeBounds = false;
    Bitmap bmp = BitmapFactory.decodeResource(a.getResources(), resId, opt);

    // 更換背景前先清掉舊的,避免殘留
    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN) {
        view.setBackground(null);
    } else {
        view.setBackgroundDrawable(null);
    }

    // 回收傳入的舊 bitmap
    if (bmpToBlur != null && !bmpToBlur.isRecycled()) {
        bmpToBlur.recycle();
    }

    bmpToBlur = blurBitmap(a, bmp);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
        view.setBackground(new BitmapDrawable(a.getResources(), bmpToBlur));
    } else {
        view.setBackgroundDrawable(new BitmapDrawable(a.getResources(), bmpToBlur));
    }
}

public static Bitmap blurBitmap(Context c, Bitmap bitmap) {
    // 建立一張同尺寸的空白 bitmap 作為輸出
    Bitmap outBitmap = Bitmap.createBitmap(
            bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_4444);

    // 建立 RenderScript 執行環境
    RenderScript rs = RenderScript.create(c.getApplicationContext());

    // 使用系統內建的模糊腳本
    ScriptIntrinsicBlur blurScript = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));

    // 配置輸入與輸出緩衝區
    Allocation allIn = Allocation.createFromBitmap(rs, bitmap);
    Allocation allOut = Allocation.createFromBitmap(rs, outBitmap);

    // 設定模糊半徑(約 0~25)
    blurScript.setRadius(25.f);

    // 執行模糊並把結果複製回 bitmap
    blurScript.setInput(allIn);
    blurScript.forEach(allOut);
    allOut.copyTo(outBitmap);

    bitmap.recycle();

    // 用畢務必釋放,否則會有記憶體洩漏
    rs.destroy();
    return outBitmap;
}

呼叫時记得做版本判斷,低版本直接退回普通背景圖:

Bitmap bitmap = null;
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {
    ImageUtil.updateBgToBlur(getActivity(), bitmap, slidingUpPanelLayout,
                             R.drawable.bg_tageditor);
} else {
    slidingUpPanelLayout.setBackgroundResource(R.drawable.bg_tageditor);
}

做法二:BlurView 懸浮模糊層

需求情境是這樣的:背景是一張紫色底圖,上面疊著相簿圖片,而 Framelayout 裡還要再蓋一層會即時模糊的視覺效果。這種「模糊結果必須跟著背後內容變動」的場景,BlurView 是最省事的方案。

引入相依

compile 'com.eightbitlab:supportrenderscriptblur:1.0.0'
compile 'com.eightbitlab:blurview:1.3.3'

defaultConfig {
    renderscriptTargetApi 25   // 需與 targetSdk 及 build tools 一致,23 以上
    renderscriptSupportModeEnabled true
}

綁定視圖

final float radius = 20;
final View decorView = getActivity().getWindow().getDecorView();

// 取得內容根容器,BlurView 會以它背後的畫面作為模糊來源
final ViewGroup rootView =
        (ViewGroup) decorView.findViewById(android.R.id.content);

// 若根佈局沒有背景,需手動提供,否則透明區域會出現異常
final Drawable windowBackground = decorView.getBackground();

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
    mBlurView.setupWith(rootView)
             .windowBackground(windowBackground)
             .blurAlgorithm(new RenderScriptBlur(getActivity()))
             .blurRadius(radius);
} else {
    mBlurView.setupWith(rootView)
             .windowBackground(windowBackground)
             .blurAlgorithm(new SupportRenderScriptBlur(getActivity()))
             .blurRadius(radius);
}

佈局檔

<eightbitlab.com.blurview.BlurView
    android:id="@+id/blurView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:blurOverlayColor="@color/colorOverlay">

    <!-- 這裡放任何子 View,例如 TabLayout -->
</eightbitlab.com.blurview.BlurView>

效能上的幾點提醒

blurOverlayColor 是必要的。純模糊的視覺在淺色背景上往往不夠,加一層半透明遮罩色能讓前景文字更清晰,這也是 iOS 毛玻璃效果的關鍵。

半徑不是越大越好。setRadius 實測在 20~25 之間還有明顯收益,再往上不僅視覺差異不明顯,效能損耗卻直線上升。

RenderScript 已被標記為 Deprecated。Android 12 之後官方建議改用 RenderEffect.createBlurEffect()(API 31+)搭配 View.setRenderEffect(),程式碼量更少且不需自行管理 Bitmap。若專案 minSdk 允許,新專案可以直接走這條路。

記得 recycle 與 destroy。做法一中的手動 Bitmap 管理很容易漏,尤其在列表捲動反覆呼叫時,記憶體回收壓力會很明顯。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved