- 截屏代码方法1
private void screenShotAll() {
View view = getWindow().getDecorView().getRootView();
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
Bitmap temBitmap = view.getDrawingCache();
File fileDir = new File(CAMERA_DIR);
if (!fileDir.exists()) {
fileDir.mkdirs();
}
String path = CAMERA_DIR + "/all_screen.png";
try {
FileOutputStream foStream = new FileOutputStream(path);
temBitmap.compress(Bitmap.CompressFormat.PNG, 100, foStream);
foStream.flush();
foStream.close();
Toast.makeText(this,"截屏成功,请在相册目录下("+path+")查看",Toast.LENGTH_LONG).show();
} catch (Exception e) {
Log.i("Show", e.toString());
}
}
由于我的需求是 游客登录时自动截屏后台分配的用户名和密码到相册,正好我这里登录是一个dialog,然后dialog并没有显示,于是了解到可以单独截取dialog
AlertDialog dialog;
private void showDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("提示");
builder.setMessage("等待1秒自动截屏dialog,请在相册目录下("+CAMERA_DIR+")查看");
builder.setIcon(R.mipmap.ic_launcher);
builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
dialog = builder.create();
dialog.show();
// window = dialog.getWindow();
}
先保存dialog,同时更改截屏方法第一行代码,通过dialog获取view
View view = dialog.getWindow().getDecorView();
截屏代码方法2
private void screenShotView(View view) { Bitmap temBitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(temBitmap); view.draw(canvas); File fileDir = new File(CAMERA_DIR); if (!fileDir.exists()) { fileDir.mkdirs(); } String path = CAMERA_DIR + "/view_screen.png"; try { FileOutputStream foStream = new FileOutputStream(path); temBitmap.compress(Bitmap.CompressFormat.PNG, 100, foStream); foStream.flush(); foStream.close(); Toast.makeText(this,"截屏成功,请在相册目录下("+path+")查看",Toast.LENGTH_LONG).show(); } catch (Exception e) { Log.i("Show", e.toString()); } }
通过dialog获取到DecorView,截取指定view保存到相册
screenShotView(dialog.getWindow().getDecorView());