螢幕截圖,dialog截圖
阿新 • • 發佈:2019-01-08
- 截圖程式碼方法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());