Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

不用 root 幫 Android 畫面截圖並存成 PNG

編輯:關於 Android 程式設計

早期 Android 要截圖幾乎一定要 root,或是接上 adb。但其實應用程式只要有自己的視窗內容,就能透過 Drawing Cache 把畫面存成圖片,完全不需要特殊權限。

三步驟完成

private void GetandSaveCurrentImage() {

    // 1. 建立與螢幕同尺寸的 Bitmap
    WindowManager windowManager = getWindowManager();
    Display display = windowManager.getDefaultDisplay();
    int w = display.getWidth();
    int h = display.getHeight();
    Bitmap Bmp = Bitmap.createBitmap(w, h, Config.ARGB_8888);

    // 2. 從 DecorView 取得 Drawing Cache
    View decorview = this.getWindow().getDecorView();
    decorview.setDrawingCacheEnabled(true);
    Bmp = decorview.getDrawingCache();

    // 3. 寫入檔案
    try {
        File path = new File(SavePATH);
        String filepath = SavePATH + "/Screen_1.png";
        File file = new File(filepath);

        if (!path.exists()) {
            path.mkdirs();
        }
        if (!file.exists()) {
            file.createNewFile();
        }

        FileOutputStream fos = null;
        fos = new FileOutputStream(file);
        if (null != fos) {
            Bmp.compress(Bitmap.CompressFormat.PNG, 90, fos);
            fos.flush();
            fos.close();
            Toast.makeText(this, "截圖已儲存", Toast.LENGTH_LONG).show();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

三個步驟的原理

1. 決定尺寸

取得螢幕的寬高,建立一塊 ARGB_8888 的 Bitmap。用 ARGB_8888 是為了保留透明通道,若確定不需要透明,用 RGB_565 可省一半記憶體。

2. 開啟 Drawing Cache 並取出

setDrawingCacheEnabled(true) 會讓 View 把自己渲染到一塊記憶體快取中,getDrawingCache() 就是取出這份快取。 DecorView 是整個視窗的根節點,所以它能涵蓋包含狀態列與標題列在內的完整畫面。

3. 壓縮存檔

compress() 的第二個參數是品質(0~100),但對 PNG 無效——PNG 是無失真格式,這個參數只對 JPEG 有效。範例寫 90 實際上沒有作用。

幾個必須修正的問題

Drawing Cache 記得要關

開啟後不關閉,會持續佔用一塊與螢幕等大的記憶體。用 decorview.setDrawingCacheEnabled(false) 收尾,或改用 buildDrawingCache() 搭配 getDrawingCache() 後立即 invalidate cache。

第一步建立的 Bitmap 是白做的

程式先 createBitmap() 建立一塊,接著又被 getDrawingCache() 的結果覆蓋。前者變成游離物件等待 GC。直接從 Drawing Cache 取用即可,不需要預先建立。

getDrawingCache() 可能回傳 null

若 View 尚未完成一次 layout / draw(例如畫面剛建立就立刻截圖),快取是空的。比較穩健的做法是呼叫 decorview.buildDrawingCache() 之後再取,並加上 null 檢查。

檔案權限與路徑

寫入外部儲存需要 WRITE_EXTERNAL_STORAGE 權限,Android 6.0 之後還要在執行期動態申請。若只是 App 內部使用,寫到 getExternalFilesDir() 或 getFilesDir() 就不需要任何權限,這是更省事的做法。

例外處理太籠統

一個 catch (Exception e) 把磁碟滿、權限不足、路徑不存在全部吞掉,問題發生時無從追查。至少該區分 IOException 並記錄訊息。

更完整的寫法

public Bitmap captureScreen() {
    View decorView = getWindow().getDecorView();
    decorView.setDrawingCacheEnabled(true);
    decorView.buildDrawingCache();
    Bitmap cache = decorView.getDrawingCache();

    if (cache == null) {
        return null;
    }

    // 複製一份,避免後續 cache 被回收影響到結果
    Bitmap result = cache.copy(Bitmap.Config.ARGB_8888, false);
    decorView.setDrawingCacheEnabled(false);

    return result;
}

public boolean saveBitmap(Bitmap bitmap, File file) {
    FileOutputStream fos = null;
    try {
        File parent = file.getParentFile();
        if (parent != null && !parent.exists()) {
            parent.mkdirs();
        }
        fos = new FileOutputStream(file);
        return bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
    } catch (IOException e) {
        Log.e("Capture", "儲存失敗", e);
        return false;
    } finally {
        if (fos != null) {
            try {
                fos.flush();
                fos.close();
            } catch (IOException ignored) {
            }
        }
    }
}

加了 copy() 這一步是因為 Drawing Cache 由 View 持有,一旦關閉快取或被回收,原本的 Bitmap 內容就不可靠了。

如果目標是整個螢幕

Drawing Cache 只能拍到「自己 App 的視窗」。若需要包含其他 App、通知列或系統 UI 的完整螢幕,Android 5.0 之後提供了 MediaProjection API:先透過系統的截圖授權對話框取得使用者同意,再建立 VirtualDisplay 錄製畫面。這是官方唯一支援的跨應用截圖途徑,也是螢幕錄影 App 的基礎。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved