创建模糊透明的背景效果



我试图使一个视图,将有一个背景,不仅是透明的,但也将有一个模糊的效果。这样,下面的景色看起来就没有焦点了。我想让它看起来像按下电源键后的屏幕。什么好主意吗?

既然窗口标志已被弃用,那么您必须模糊自己。我在其他地方回答了这个问题,但这里是如何模糊视图:

你现在可以使用RenderScript库中的ScriptIntrinsicBlur来快速模糊。下面是如何访问RenderScript API。下面是我用来模糊视图和位图的类:

import android.support.v8.renderscript.*;
public class BlurBuilder {
    private static final float BITMAP_SCALE = 0.4f;
    private static final float BLUR_RADIUS = 7.5f;
    public static Bitmap blur(View v) {
        return blur(v.getContext(), getScreenshot(v));
    }
    public static Bitmap blur(Context ctx, Bitmap image) {
        int width = Math.round(image.getWidth() * BITMAP_SCALE);
        int height = Math.round(image.getHeight() * BITMAP_SCALE);
        Bitmap inputBitmap = Bitmap.createScaledBitmap(image, width, height, false);
        Bitmap outputBitmap = Bitmap.createBitmap(inputBitmap);
        RenderScript rs = RenderScript.create(ctx);
        ScriptIntrinsicBlur theIntrinsic = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));
        Allocation tmpIn = Allocation.createFromBitmap(rs, inputBitmap);
        Allocation tmpOut = Allocation.createFromBitmap(rs, outputBitmap);
        theIntrinsic.setRadius(BLUR_RADIUS);
        theIntrinsic.setInput(tmpIn);
        theIntrinsic.forEach(tmpOut);
        tmpOut.copyTo(outputBitmap);
        return outputBitmap;
    }
    private static Bitmap getScreenshot(View v) {
        Bitmap b = Bitmap.createBitmap(v.getWidth(), v.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas c = new Canvas(b);
        v.draw(c);
        return b;
    }
}

要将此应用于片段,请将以下内容添加到onCreateView:

final Activity activity = getActivity();
final View content = activity.findViewById(android.R.id.content).getRootView();
if (content.getWidth() > 0) {
    Bitmap image = BlurBuilder.blur(content);
    window.setBackgroundDrawable(new BitmapDrawable(activity.getResources(), image));
} else {
    content.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            Bitmap image = BlurBuilder.blur(content);
            window.setBackgroundDrawable(new BitmapDrawable(activity.getResources(), image));
        }
    });
}

注意:此解决方案要求最小sdk为API 17

EDIT: Renderscript包含在支持v8中,使这个答案下降到api 8。要使用gradle将这些行包含到gradle文件中(从这个答案中),并使用包android.support.v8.renderscript:

中的Renderscript来启用它
android {
  ...
  defaultConfig {
    ...
    renderscriptTargetApi *your target api*
    renderscriptSupportModeEnabled true
  }
  ...
}

如果所有你想做的是模糊你的活动背后的窗口的背景,那么你可以使用这个调用从你的活动(或任何类,如AlertDialog有一个窗口)

getWindow().addFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND);

更新:此标志在Android 4.0中已弃用,不再工作

模糊是一个很好的选择,可以很容易地给你你正在寻找的效果:https://github.com/wasabeef/Blurry

添加到项目后,将想要模糊的视图包装在framayout中,然后在想要模糊时使用这一行:

Blurry.with(this).radius(25).sampling(2).onto((ViewGroup) findViewById(R.id.viewToBlurWrapper));