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

Android 螢幕截圖功能實作:DrawingCache 用法解析

編輯:關於 Android 程式設計

「分享這一刻」是許多 app 都會有的功能,而要在使用者不按下硬體鍵的前提下取得畫面,最簡單的途徑就是 View.setDrawingCacheEnabled()。原理是讓 View 把當前內容繪製到一塊記憶體快取中,我們再把這塊快取取出來轉成 Bitmap。

package net.canking.shottest;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.view.View;

public class ScreenShot {

    private static Bitmap takeScreenShot(Activity activity) {
        // 指定要截圖的 View,這裡取整個視窗
        View view = activity.getWindow().getDecorView();
        view.setDrawingCacheEnabled(true);
        view.buildDrawingCache();
        Bitmap b1 = view.getDrawingCache();

        // 取得狀態列高度,準備裁掉
        Rect frame = new Rect();
        activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
        int statusBarHeight = frame.top;

        // 取得螢幕寬高
        int width = activity.getWindowManager().getDefaultDisplay().getWidth();
        int height = activity.getWindowManager().getDefaultDisplay().getHeight();

        // 去掉狀態列後裁切
        Bitmap b = Bitmap.createBitmap(b1, 0, statusBarHeight, width, height - statusBarHeight);
        view.destroyDrawingCache();
        return b;
    }

    private static void savePic(Bitmap b, File filePath) {
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(filePath);
            if (null != fos) {
                b.compress(Bitmap.CompressFormat.PNG, 100, fos);
                fos.flush();
                fos.close();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void shoot(Activity a, File filePath) {
        if (filePath == null) return;
        if (!filePath.getParentFile().exists()) {
            filePath.getParentFile().mkdirs();
        }
        ScreenShot.savePic(ScreenShot.takeScreenShot(a), filePath);
    }
}

幾個實作細節

為什麼要裁狀態列:getDecorView() 拿到的是包含系統狀態列的整個視窗,若不需要狀態列,就要透過 getWindowVisibleDisplayFrame() 取得狀態列高度再裁切。相對地,若想連標題列一起去掉,就改用 content 這個子 View 當截圖來源。

一定要 destroyDrawingCache:這塊快取佔用可觀的記憶體,用完不釋放會直接推向 OOM。範例中已正確呼叫。

硬體加速的限制:在開啟硬體加速的機型上,某些自繪內容(例如部分 OpenGL 渲染)不會被 DrawingCache 正確擷取。遇到這種情況需要改用 PixelCopy(API 24 以上)或 MediaProjection 進行真正的螢幕擷取。

權限與儲存位置:Android 10 之後不建議直接寫外部儲存空間,應改用 MediaStore 或 app 專用目錄;同時記得在 manifest 中依目標 SDK 版本宣告對應權限。

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