这个android截图的方法就是使用View.getDrawingCache()方法,缺点是只有视图完全显示才能获取到,而且不能获取Dialog,PopupWindows,Toast
//获取顶级视图,包括标题栏,但不包括状态栏。
View decorView = activity.getWindow().getDecorView();
decorView.setDrawingCacheEnabled(true);
decorView.buildDrawingCache();
Bitmap bitmap = decorView.getDrawingCache();
这样获取的Bitmap大小就是屏幕分辨率的大小,当然也可以进行一下处理
Bitmap createScaledBitmap = Bitmap.createScaledBitmap(bitmap, width,height, true);
之后将截图保存到本地就可以了,file为保存路径
try {
FileOutputStream fs = new FileOutputStream(file);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
//这个方法的第一个参数是保存的图片格式,但只能保存三种格式JPG,PNG,WEBP。第二个参数是图片压缩率,压缩率为0到100,否则会抛 IllegalArgumentException(“quality must be 0..100”); 数值越小压缩出的图片越小,但是清晰度会下降,对于PNG等无损格式的图片,会忽略此项设置。
createScaledBitmap.compress(Bitmap.CompressFormat.JPEG, 10,
baos);
fs.write(baos.toByteArray());
fs.close();
baos.flush();
baos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}