Android開發中實現整個屏幕截圖,首先通過activity對象的getwindow()方法獲得整個屏幕的window對象,再通過整個屏幕的window對象的getDecorView()方法獲得整個屏幕的view,最後截圖的實現,也就是將view轉換成bitmap,然後,將bitmap保存為圖片文件。
Java代碼
- public static Bitmap takeScreenShot(Activity act) {
- if (act == null || act.isFinishing()) {
- Log.d(TAG, "act參數為空.");
- return null;
- }
-
- // 獲取當前視圖的view
- View scrView = act.getWindow().getDecorView();
- scrView.setDrawingCacheEnabled(true);
- scrView.buildDrawingCache(true);
-
- // 獲取狀態欄高度
- Rect statuBarRect = new Rect();
- scrView.getWindowVisibleDisplayFrame(statuBarRect);
- int statusBarHeight = statuBarRect.top;
- int width = act.getWindowManager().getDefaultDisplay().getWidth();
- int height = act.getWindowManager().getDefaultDisplay().getHeight();
-
- Bitmap scrBmp = null;
- try {
- // 去掉標題欄的截圖
- scrBmp = Bitmap.createBitmap( scrView.getDrawingCache(), 0, statusBarHeight,
- width, height - statusBarHeight);
- } catch (IllegalArgumentException e) {
- Log.d("", "#### 旋轉屏幕導致去掉狀態欄失敗");
- }
- scrView.setDrawingCacheEnabled(false);
- scrView.destroyDrawingCache();
- return scrBmp;
- }