背景毛玻璃实现效果:高斯模糊
毛玻璃效果:高斯模糊实现
![](https://images0.cnblogs.com/blog/701374/201507/211034107385293.jpg)
这里是把新生成的页面以上一个页面为高斯模糊的底。
首先这里需要处理的一个问题是,上一个界面截屏。
1、获取上一界面的截图 :
-
View view = activity.getWindow().getDecorView(); view.setDrawingCacheEnabled(true); view.buildDrawingCache(); Bitmap b1 = view.getDrawingCache();
DecorView是最顶端的View,在当前Activity中只有当运行到了onWindowFocusChanged的时候才能获取到View。
publicvoid onWindowFocusChanged(boolean hasFocus){ super.onWindowFocusChanged(hasFocus); View view = getWindow().getDecorView(); view.setDrawingCacheEnabled(true); view.buildDrawingCache(true); blur(bmp1,bgLayout); }
在第二个Activity中使用Activity管理类获取上一个Activity的实例。需要做的去掉顶部的view。
-
/** * 将一个Activity截图 * * @param activity * @return */ privateBitmap takeScreenShot(Activity activity){ View view = activity.getWindow().getDecorView(); view.setDrawingCacheEnabled(true); view.buildDrawingCache(); Bitmap b1 = view.getDrawingCache(); // 获取状态栏高度 Rect frame =newRect(); activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame); int statusBarHeight = frame.top; // 获取屏幕长和高 DisplayMetrics dm =newDisplayMetrics(); activity.getWindowManager().getDefaultDisplay().getMetrics(dm); int width = dm.widthPixels; int height = dm.heightPixels; // 去掉标题栏 Bitmap b =Bitmap.createBitmap(b1,0, statusBarHeight, width, height - statusBarHeight); view.destroyDrawingCache(); return b; }
2、做高斯模糊。
一般用的3种方法,第一种使用RenderScript;第二种使用开源的FastBlur;第三种使用的是优化了的FastBlur,即对FastBlur的
bitmap先放大尺寸再缩小,使其损失部分像素点,从而提高效率,避免OOM。所以推荐第三种。
-
private void blur(Bitmap bkg,ViewGroup view){ long startMs =System.currentTimeMillis(); float scaleFactor =4;// 图片缩放比例; float radius =20;// 模糊程度 int width =(int) view.getMeasuredWidth(); int height =(int) view.getMeasuredHeight(); Bitmap overlay =Bitmap.createBitmap((int)(width / scaleFactor), (int)(height / scaleFactor),Bitmap.Config.ARGB_8888); Canvas canvas =newCanvas(overlay); canvas.translate(-view.getLeft()/ scaleFactor,-view.getTop() / scaleFactor); canvas.scale(1/ scaleFactor,1/ scaleFactor); Paint paint =newPaint(); paint.setFlags(Paint.FILTER_BITMAP_FLAG); canvas.drawBitmap(bkg,0,0, paint); overlay =FastBlur.doBlur(overlay,(int) radius,true); view.setBackground(newBitmapDrawable(getResources(), overlay)); /** * 打印高斯模糊处理时间,如果时间大约16ms,用户就能感到到卡顿,时间越长卡顿越明显,如果对模糊完图片要求不高, * 可是将scaleFactor设置大一些。 */ Log.i("jerome","blur time:"+(System.currentTimeMillis()- startMs)); }
blur的参数可以改成View或者ViewGroup,看情况,这个View是需要设置背景的控件。
还有一点。本方法放的位置:
onWindowFocusChaged方法里面;
或者是该View的回调事件使用;
或者onResume方法最后开线程300毫秒左右后获取宽和高 因为onResume执行完后300毫秒后 界面就显示出来了如onClick;
因为View.getgetMeasuredHeight()来获得某个view的宽度或高度,但是在onCreate()、onStrart()、onResume()
方法中会返回0,这是应为当前activity所代表的界面还没显示出来没有添加到WindowPhone的DecorView上或要获
取的view没有被添加到DecorView上或者该View的visibility属性为gone 或者该view的width或height真的为0所以
只有上述条件都不成立时才能得到非0的width和height。
Demo:MaoGlassDemo
勿忘初衷