获取屏幕保存成图片,其实就是一个截图功能,只不过这个截图是截不到状态栏的。
看注释,通过下面的代码我们就得到了当前界面的Bitmap。1
2
3
4
5
6
7
8
9
10
11
12
13
14//获取当前屏幕的大小
int width = activity.getWindow().getDecorView().getRootView().getWidth();
int height = activity.getWindow().getDecorView().getRootView().getHeight();
//生成相同大小的图片
Bitmap temBitmap = Bitmap.createBitmap( width, height, Bitmap.Config.ARGB_8888 );
//找到当前页面的跟布局
View view = activity.getWindow().getDecorView().getRootView();
//清除缓存
view.destroyDrawingCache();
//设置缓
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
//从缓存中获取当前屏幕的图片
temBitmap = view.getDrawingCache();
拿到Bitmap之后我们就可以进行一些保存操作1
2
3
4
5
6
7
8
9
10
11
12
13
14
15try {
//保存路径,这个路径是项目的私有路径
File file=new File(context.getFilesDir().getPath()+"/disk.jpg");
file.delete();
FileOutputStream fos = new FileOutputStream(file);
//图片,可以进行压缩,然后保存
temBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
//清空并关闭
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}