项目测试中有个需求是截取当前屏幕所显示的内容,并且截屏并保存到指定文件夹中。
主流方法之一是获取当前屏幕View并保存为bitmap对象,之后bitmap保存到指定文件夹即可。
下面是从网络上整理得到的代码:public static Bitmap takeScreenShot(Activity activity) {
// 准备截图要保存的View
View view = activity.getWindow().getDecorView();
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
Bitmap b1 = view.getDrawingCache();
// 获取状态栏高度
Rect frame = new Rect();
activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
int statusBarHeight = frame.top;
// 获取屏幕长和高
int width = activity.getWindowManager().getDefaultDisplay().getWidth();
int height = activity.getWindowManager().getDefaultDisplay().getHeight();
// 去掉标题栏
Bitmap b = Bitmap.createBitmap(b1, 0, statusBarHeight, width, height
- statusBarHeight);
view.destroyDrawingCache()