Android实现对Dialog的截图并保存在本地

时间:2022-06-06 08:27:13

直接上代码:

public class TestDilaog extends Dialog {
public TestDilaog(@NonNull Context context) {
super(context, R.style.UpdateDialogTheme);
}

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.xxxx);
//必须加这两句代码
this.getWindow().getDecorView().setDrawingCacheEnabled(true);
this.getWindow().getDecorView().buildDrawingCache();
}
//将图像保存到SD卡中
public void saveMyBitmap(){
if(!ImageTools.checkSDCardAvailable()){
T.show("SD卡不可用,保存失败");
return;
}
String currentPath= DemoApplication.GalleryPhoto+"/" +System.currentTimeMillis() + ".jpg";
File f = new File(currentPath);
try {
f.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
}
FileOutputStream fOut = null;
try {
fOut = new FileOutputStream(f);
} catch (Exception e) {
e.printStackTrace();
}
//获取bitmap关键代码
View dialogView = this.getWindow().getDecorView();
Bitmap dialogBitmap=dialogView.getDrawingCache();
dialogBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
try {
fOut.flush();
} catch (IOException e) {
e.printStackTrace();
}
try {
fOut.close();
} catch (IOException e) {
e.printStackTrace();
}
Toast.makeText(context,"图片保存到了"+currentPath,Toast.LENGTH_LONG).show();
MediaScannerConnection.scanFile(context, new String[]{currentPath}, null, null);
}
}