先看效果
再看实现思路
第一种:
创建全屏的dialog,然后拿到宿主activity(decorView)的DrawingCacheBitmap做高斯模糊,再将高斯模糊后的Bitmap设置给dialog做背景;
第二种:
创建dialog时,拿到宿主activity(decorView),创建一个ImageView add到decorView 中,然后给ImageView设置高斯模糊背景,根据dialog的状态去控制ImageView(下面的实现是用的第二种);
动手上代码
1.创建一个BlurDialog.java
public class BlurDialogextends Dialog {
......
}
2.创建BlurView add到decorView中
ViewGroup decorView = (ViewGroup) activity.getWindow().getDecorView();
mBlurView = decorView.findViewById(R.id.blur_dialog_bg);
if(mBlurView ==null){
mBlurView =new BlurView(activity);
mBlurView.setId(R.id.blur_dialog_bg);
mBlurView.setAlpha(0f);
decorView.addView(mBlurView, new ViewGroup.LayoutParams(-1,-1));
}
(在这里将mBlurView的Alpha设置为0是为了在后面展示隐藏式做渐变动画,视觉效果更高级一点点点点~)
3.在onCreate()中给BlurView设置高斯模糊背景
<1>
View decorView1 = activity.getWindow().getDecorView();
//创建一个与decorView大小一样的bitmap
Bitmap bitmap = Bitmap.createBitmap(decorView1.getWidth(), decorView1.getHeight(), Bitmap.Config.ARGB_8888);
//创建一个画布将bitmap传进去
Canvas canvas =new Canvas(bitmap);
//将decorView绘制在canvas上,相当于绘制到bitmap上了
decorView1.draw(canvas);
mBlurView.setBackground(new BitmapDrawable(getResources(), BlurUtils.blur(activity, bitmap, 4, 0.2f)));
<2>
public final class BlurUtils {
private static RenderScript renderScript;
private static ScriptIntrinsicBlur scriptIntrinsicBlur;
public static Bitmapblur(Context context, Bitmap source, int radius, float scale){
int width = Math.round(source.getWidth() * scale);
int height = Math.round(source.getHeight() * scale);
Bitmap inputBmp = Bitmap.createScaledBitmap(source,width,height,true);
if(renderScript ==null) {
renderScript = RenderScript.create(context.getApplicationContext());
}
// Allocate memory for Renderscript to work with
final Allocation input = Allocation.createFromBitmap(renderScript,inputBmp);
final Allocation output = Allocation.createTyped(renderScript,input.getType());
// Load up an instance of the specific script that we want to use.
if(scriptIntrinsicBlur ==null) {
scriptIntrinsicBlur = ScriptIntrinsicBlur.create(renderScript, Element.U8_4(renderScript));
}
scriptIntrinsicBlur.setInput(input);
// Set the blur radius
scriptIntrinsicBlur.setRadius(radius);
// Start the ScriptIntrinisicBlur
scriptIntrinsicBlur.forEach(output);
// Copy the output to the blurred bitmap
output.copyTo(inputBmp);
renderScript.destroy();
return inputBmp;
}
}
(这里RenderScript ScriptIntrinsicBlur 的创建比较耗时(300ms左右),建议提前创建,不然第一次的时候会卡一下)
4.在dialog onAttachedToWindow()中展示BlurView,在onDetachedFromWindow()中隐藏BlurView
public void onAttachedToWindow() {
super.onAttachedToWindow();
BlurView.animate().alpha(1f).setDuration(300).start();
}
public void onDetachedFromWindow() {
super.onDetachedFromWindow();
BlurView.animate().alpha(0f).setDuration(300).start();
}