我們知道,控件都是通過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();
}