我们知道,控件都是通过Canvas进行绘制而呈现出来的 如果我们将Canvas的绘制过程缓存起来,再将其写入到位图中,那么就可以得到这个控件的图像 如果我们对DecorView(Window布局的根节点)的Canvas进行缓存捕捉,那么就可以得到整个界面的图像 Bitmap对象本身带有裁剪的功能,我们只要知道屏幕坐标,按坐标对Bitmap进行裁剪,就可以得到屏幕任意区域的图像
这个方法适合绝大多数控件,但不适合于SurfaceView等控件,因为它的工作原理与一般View不同
View decorView = getWindow().getDecorView();
//开启绘制缓存
decorView.setDrawingCacheEnabled(true);
decorView.buildDrawingCache();
//将画布缓存写入到位图中
Bitmap screenBitmap = decorView.getDrawingCache();
//位图裁剪,只保留指定控件部分
int[] location = new int[2];
view.getLocationInWindow(location);
Bitmap clipBitmap = screenBitmap.createBitmap(
screenBitmap,
location[0],
location[1],
view.getMeasuredWidth(),
view.getMeasuredHeight()
);
//写入文件
Bitmaps.writeBitmapToFile(clipBitmap, "sdcard/1.png", 100);
//清空绘制缓存
decorView.setDrawingCacheEnabled(false);
screenBitmap.recycle();
clipBitmap.recycle();
@SneakyThrows
public static void writeBitmapToFile(Bitmap bitmap, String dst, int quality) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, quality, bos);
bitmap.recycle();
FileOutputStream fos = new FileOutputStream(dst);
fos.write(bos.toByteArray());
fos.flush();
fos.close();
bos.close();
}