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

getDrawingCache() 與 Android 常見截屏方案盤點

編輯:關於 Android 開發

getDrawingCache() 與 Android 常見截屏方案盤點

一、用 getDrawingCache() 截取局部畫面

view.setDrawingCacheEnabled(true); // 開啟圖片緩存(drawing cache)
view.buildDrawingCache();          // 若可緩存,則構建圖片緩存
Bitmap bitmap = view.getDrawingCache(); // 若已緩存,返回一個 Bitmap
view.destroyDrawingCache();        // 釋放緩存佔用的資源

幾點提醒:

如果同一界面裡反覆截圖,每次截屏前都應先清掉緩存;

如果截出的圖不符合預期,可以用 Bitmap.createBitmap() 再處理(注意壓縮過度會導致圖片無法顯示)。

把圖片存到本地

File f = new File(" ");
try {
    f.createNewFile();
} catch (IOException e1) {
    e1.printStackTrace();
}
FileOutputStream fOut = null;
try {
    fOut = new FileOutputStream(f);
} catch (FileNotFoundException e) {
    e.printStackTrace();
}
mBitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);
try {
    fOut.flush();
} catch (IOException e) {
    e.printStackTrace();
}
try {
    fOut.close();
} catch (IOException e) {
    e.printStackTrace();
}

其他截屏方案

1、在 APK 中調用 "adb shell screencap -p filepath" 命令(基於 Android SDK 的截屏方式)

這條命令會讀取系統的 framebuffer,需要系統權限:

(1)在 AndroidManifest.xml 中添加相應聲明;

(2)把 APK 提權為系統權限,放進源碼一起編譯,修改 Android.mk:

LOCAL_CERTIFICATE := platform

public void takeScreenShot() {
    String mSavedPath = Environment.getExternalStorageDirectory() + File.separator + "screenshot.png";
    try {
        Runtime.getRuntime().exec("screencap -p " + mSavedPath);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

2、利用系統 API 實現 Screenshot(相關代碼是系統隱藏的,需在源碼下編譯)

(1)在 AndroidManifest.xml 中添加相應聲明;

(2)把 APK 提權為系統權限,放進源碼一起編譯,修改 Android.mk:

LOCAL_CERTIFICATE := platform

public boolean takeScreenShot(String imagePath) {
    if (imagePath.equals("")) {
        imagePath = Environment.getExternalStorageDirectory() + File.separator + "Screenshot.png";
    }
    Bitmap mScreenBitmap;
    WindowManager mWindowManager;
    DisplayMetrics mDisplayMetrics;
    Display mDisplay;
    mWindowManager = (WindowManager) mcontext.getSystemService(Context.WINDOW_SERVICE);
    mDisplay = mWindowManager.getDefaultDisplay();
    mDisplayMetrics = new DisplayMetrics();
    mDisplay.getRealMetrics(mDisplayMetrics);
    float[] dims = { mDisplayMetrics.widthPixels, mDisplayMetrics.heightPixels };
    mScreenBitmap = Surface.screenshot((int) dims[0], (int) dims[1]);
    if (mScreenBitmap == null) {
        return false;
    }
    try {
        FileOutputStream out = new FileOutputStream(imagePath);
        mScreenBitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
    } catch (Exception e) {
        return false;
    }
    return true;
}

3、基於 Android ddmlib 截屏

public class ScreenShot {
    private BufferedImage image = null;

    public static void main(String[] args) {
        AndroidDebugBridge.init(false);
        ScreenShot screenshot = new ScreenShot();
        IDevice device = screenshot.getDevice();
        for (int i = 0; i < 10; i++) {
            Date date = new Date();
            SimpleDateFormat df = new SimpleDateFormat("MM-dd-HH-mm-ss");
            String nowTime = df.format(date);
            screenshot.getScreenShot(device, "Robotium" + nowTime);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public void getScreenShot(IDevice device, String filename) {
        RawImage rawScreen = null;
        try {
            rawScreen = device.getScreenshot();
        } catch (TimeoutException e) {
            e.printStackTrace();
        } catch (AdbCommandRejectedException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (rawScreen != null) {
            Boolean landscape = false;
            int width2 = landscape ? rawScreen.height : rawScreen.width;
            int height2 = landscape ? rawScreen.width : rawScreen.height;
            if (image == null) {
                image = new BufferedImage(width2, height2, BufferedImage.TYPE_INT_RGB);
            } else {
                if (image.getHeight() != height2 || image.getWidth() != width2) {
                    image = new BufferedImage(width2, height2, BufferedImage.TYPE_INT_RGB);
                }
            }
            int index = 0;
            int indexInc = rawScreen.bpp >> 3;
            for (int y = 0; y < rawScreen.height; y++) {
                for (int x = 0; x < rawScreen.width; x++, index += indexInc) {
                    int value = rawScreen.getARGB(index);
                    if (landscape) image.setRGB(y, rawScreen.width - x - 1, value);
                    else image.setRGB(x, y, value);
                }
            }
            try {
                ImageIO.write((RenderedImage) image, "PNG", new File("D:/" + filename + ".jpg"));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private IDevice getDevice() {
        IDevice device;
        AndroidDebugBridge bridge = AndroidDebugBridge.createBridge("adb", true);
        waitDevicesList(bridge);
        IDevice devices[] = bridge.getDevices();
        device = devices[0];
        return device;
    }

    private void waitDevicesList(AndroidDebugBridge bridge) {
        int count = 0;
        while (bridge.hasInitialDeviceList() == false) {
            try {
                Thread.sleep(500);
                count++;
            } catch (InterruptedException e) {
            }
            if (count > 240) {
                System.err.print("等待獲取設備超時");
                break;
            }
        }
    }
}

4、Android 本地編程(Native)讀取 framebuffer

先說說 framebuffer。幀緩衝(framebuffer)是 Linux 為顯示設備提供的一種接口,它把顯存抽象成一個設備,允許上層應用程序在圖形模式下直接讀寫顯示緩衝區。這種操作是統一而抽象的,用戶不必關心物理顯存的位置、換頁機制等細節,這些都由 Framebuffer 設備驅動完成。

從本質上看,Linux FrameBuffer 只是對圖形設備做了硬件抽象。在開發者眼裡,它就是一塊顯示緩存,往裡寫入特定格式的數據,就等於向屏幕輸出內容,好比一塊白板。以初始為 16 位色的 FrameBuffer 為例,其中兩個字節代表屏幕上一個點,從上到下、從左到右,屏幕位置與內存地址是線性順序對應的。顯示控制器會自動從 frame buffer 取數據並顯示,全部圖形共享內存中同一個幀緩存。

Android 基於 Linux 內核,自然也存在 framebuffer 設備。要實現截屏,只要能拿到 framebuffer 裡的數據,再把它轉換成圖片即可。Android 中這份數據存放在 /dev/graphics/fb0 文件裡,所以只要讀取該文件就能得到當前屏幕內容。測試代碼通過 RC(remote controller)方式運行被測應用時,需要在 PC 上訪問模擬器或真機上的 framebuffer,這可以借助 ADB 命令實現。

代碼實現:

public class ScreenShot {
    public static void main(String[] args) throws InterruptedException {
        try {
            // 分辨率,後續可通過代碼獲取當前分辨率
            int xResolution = 320;
            int yResolution = 480;
            // 執行 adb 命令,把 framebuffer 內容保存到 fb1
            Runtime.getRuntime().exec("adb pull /dev/graphics/fb0 C:/fb1");
            // 等待幾秒,確保數據寫入完成,否則讀取時會有 IO 異常
            Thread.sleep(15000);
            InputStream in = (InputStream) new FileInputStream("C:/fb1");
            DataInput frameBuffer = new LittleEndianDataInputStream(in);
            BufferedImage screenImage = new BufferedImage(xResolution, yResolution, BufferedImage.TYPE_INT_ARGB);
            int[] oneLine = new int[xResolution];
            for (int y = 0; y < yResolution; y++) {
                convertToRgba32(frameBuffer, oneLine);
                screenImage.setRGB(0, y, xResolution, 1, oneLine, 0, xResolution);
            }
            Closeables.closeQuietly(in);
            ByteArrayOutputStream rawPngStream = new ByteArrayOutputStream();
            if (!ImageIO.write(screenImage, "png", rawPngStream)) {
                throw new RuntimeException("This Java environment does not support converting to PNG.");
            }
            byte[] rawPngBytes = rawPngStream.toByteArray();
            String base64Png = new Base64Encoder().encode(rawPngBytes);
            File screenshot = OutputType.FILE.convertFromBase64Png(base64Png);
            screenshot.renameTo(new File("C:\\screenshottemp.png"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void convertToRgba32(DataInput frameBuffer, int[] into) {
        try {
            for (int x = 0; x < into.length; x++) {
                int rgb = frameBuffer.readShort() & 0xffff;
                int red = rgb >> 11;
                red = (red << 3) | (red >> 2);
                int green = (rgb >> 5) & 63;
                green = (green << 2) | (green >> 4);
                int blue = rgb & 31;
                blue = (blue << 3) | (blue >> 2);
                into[x] = 0xff000000 | (red << 16) | (green << 8) | blue;
            }
        } catch (IOException exception) {
            System.out.println("convertToRgba32Exception=" + exception);
        }
    }
}

另一種做法是在 Activity 裡調用 Surface 截屏,並處理屏幕旋轉:

public class SimpleScreenshotActivity extends Activity {
    private Display mDisplay;
    private WindowManager mWindowManager;
    private DisplayMetrics mDisplayMetrics;
    private Bitmap mScreenBitmap;
    private Matrix mDisplayMatrix;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        new Thread(new Runnable() {
            @Override
            public void run() {
                takeScreenshot();
            }
        }).start();
    }

    private float getDegreesForRotation(int value) {
        switch (value) {
            case Surface.ROTATION_90: return 360f - 90f;
            case Surface.ROTATION_180: return 360f - 180f;
            case Surface.ROTATION_270: return 360f - 270f;
        }
        return 0f;
    }

    private void takeScreenshot() {
        mWindowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        mDisplay = mWindowManager.getDefaultDisplay();
        mDisplayMetrics = new DisplayMetrics();
        mDisplay.getRealMetrics(mDisplayMetrics);
        mDisplayMatrix = new Matrix();
        float[] dims = { mDisplayMetrics.widthPixels, mDisplayMetrics.heightPixels };
        int value = mDisplay.getRotation();
        String hwRotation = SystemProperties.get("ro.sf.hwrotation", "0");
        if (hwRotation.equals("270") || hwRotation.equals("90")) {
            value = (value + 3) % 4;
        }
        float degrees = getDegreesForRotation(value);
        boolean requiresRotation = (degrees > 0);
        if (requiresRotation) {
            mDisplayMatrix.reset();
            mDisplayMatrix.preRotate(-degrees);
            mDisplayMatrix.mapPoints(dims);
            dims[0] = Math.abs(dims[0]);
            dims[1] = Math.abs(dims[1]);
        }
        mScreenBitmap = Surface.screenshot((int) dims[0], (int) dims[1]);
        if (requiresRotation) {
            Bitmap ss = Bitmap.createBitmap(mDisplayMetrics.widthPixels, mDisplayMetrics.heightPixels, Bitmap.Config.ARGB_8888);
            Canvas c = new Canvas(ss);
            c.translate(ss.getWidth() / 2, ss.getHeight() / 2);
            c.rotate(degrees);
            c.translate(-dims[0] / 2, -dims[1] / 2);
            c.drawBitmap(mScreenBitmap, 0, 0, null);
            c.setBitmap(null);
            mScreenBitmap = ss;
        }
        if (mScreenBitmap == null) {
            return;
        }
        mScreenBitmap.setHasAlpha(false);
        mScreenBitmap.prepareToDraw();
        try {
            saveBitmap(mScreenBitmap);
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }

    public void saveBitmap(Bitmap bitmap) throws IOException {
        String imageDate = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss")
                .format(new Date(System.currentTimeMillis()));
        File file = new File("/mnt/sdcard/Pictures/" + imageDate + ".png");
        if (!file.exists()) {
            file.createNewFile();
        }
        FileOutputStream out;
        try {
            out = new FileOutputStream(file);
            if (bitmap.compress(Bitmap.CompressFormat.PNG, 70, out)) {
                out.flush();
                out.close();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

注意:需在 AndroidManifest.xml 中加上 android:sharedUserId="android.uid.system";由於調用了 @hide 的 API,編譯時請用 makefile,或在 Eclipse 中添加對應 Jar 再編譯;此代碼在 Android 4.0 上驗證過,2.3 未做測試。

5、系統自帶組合鍵截屏的原理(TakeScreenShotService)

Android 手機一般都自帶截屏功能:在任意界面按下組合鍵,屏幕一閃、咔嚓一聲,截圖就存進了圖庫。以手上的測試機為例,是同時按電源鍵 + 音量下鍵;蘋果是電源鍵 + HOME 鍵;小米是菜單鍵 + 音量下鍵;HTC 一般是按住電源鍵再按左下角的主頁鍵。那麼源碼裡是如何捕獲組合鍵並完成截屏的呢?可分兩部分來看。

首先是組合鍵的捕獲。Android 源碼中對按鍵的捕獲位於 PhoneWindowManager.java,這個類處理所有鍵盤輸入事件,其中 interceptKeyBeforeQueueing() 會對常用按鍵做特殊處理。以電源鍵 + 音量下鍵為例,會看到類似下面的代碼:

case KeyEvent.KEYCODE_VOLUME_DOWN:
case KeyEvent.KEYCODE_VOLUME_UP:
case KeyEvent.KEYCODE_VOLUME_MUTE: {
    if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
        if (down) {
            if (isScreenOn && !mVolumeDownKeyTriggered && (event.getFlags() & KeyEvent.FLAG_FALLBACK) == 0) {
                mVolumeDownKeyTriggered = true;
                mVolumeDownKeyTime = event.getDownTime();
                mVolumeDownKeyConsumedByScreenshotChord = false;
                cancelPendingPowerKeyAction();
                interceptScreenshotChord();
            }
        } else {
            mVolumeDownKeyTriggered = false;
            cancelPendingScreenshotChordAction();
        }
    }
    ...
}
case KeyEvent.KEYCODE_POWER: {
    result &= ~ACTION_PASS_TO_USER;
    if (down) {
        if (isScreenOn && !mPowerKeyTriggered && (event.getFlags() & KeyEvent.FLAG_FALLBACK) == 0) {
            mPowerKeyTriggered = true;
            mPowerKeyTime = event.getDownTime();
            interceptScreenshotChord();
        }
    }
    ...
}

可以看到,正是在響應 Down 事件時捕獲音量下鍵和電源鍵,兩處都會進入 interceptScreenshotChord()。這個函數做了什麼?

private void interceptScreenshotChord() {
    if (mVolumeDownKeyTriggered && mPowerKeyTriggered && !mVolumeUpKeyTriggered) {
        final long now = SystemClock.uptimeMillis();
        if (now <= mVolumeDownKeyTime + SCREENSHOT_CHORD_DEBOUNCE_DELAY_MILLIS
                && now <= mPowerKeyTime + SCREENSHOT_CHORD_DEBOUNCE_DELAY_MILLIS) {
            mVolumeDownKeyConsumedByScreenshotChord = true;
            cancelPendingPowerKeyAction();
            mHandler.postDelayed(mScreenshotChordLongPress, ViewConfiguration.getGlobalActionKeyTimeout());
        }
    }
}

這裡用兩個布爾變量判斷是否同時按下了音量下鍵和電源鍵,再計算兩個按鍵 Down 事件之間的時間差不超過 150 毫秒,就認定為真正的截屏組合鍵。(附帶一提,PhoneWindowManager.java 這個攔截鍵盤消息的類裡,還處理了 home 鍵、返回鍵等諸多按鍵。)

捕獲到組合鍵後,再看源碼如何調用截屏接口。長按組合鍵 500 毫秒後會進入:

private final Runnable mScreenshotChordLongPress = new Runnable() {
    public void run() {
        takeScreenshot();
    }
};

這裡啟動了一個線程来完成截屏,接著看 takeScreenshot():

private void takeScreenshot() {
    synchronized (mScreenshotLock) {
        if (mScreenshotConnection != null) {
            return;
        }
        ComponentName cn = new ComponentName("com.android.systemui",
                "com.android.systemui.screenshot.TakeScreenshotService");
        Intent intent = new Intent();
        intent.setComponent(cn);
        ServiceConnection conn = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                synchronized (mScreenshotLock) {
                    if (mScreenshotConnection != this) {
                        return;
                    }
                    Messenger messenger = new Messenger(service);
                    Message msg = Message.obtain(null, 1);
                    final ServiceConnection myConn = this;
                    Handler h = new Handler(mHandler.getLooper()) {
                        @Override
                        public void handleMessage(Message msg) {
                            synchronized (mScreenshotLock) {
                                if (mScreenshotConnection == myConn) {
                                    mContext.unbindService(mScreenshotConnection);
                                    mScreenshotConnection = null;
                                    mHandler.removeCallbacks(mScreenshotTimeout);
                                }
                            }
                        }
                    };
                    msg.replyTo = new Messenger(h);
                    msg.arg1 = msg.arg2 = 0;
                    if (mStatusBar != null && mStatusBar.isVisibleLw()) msg.arg1 = 1;
                    if (mNavigationBar != null && mNavigationBar.isVisibleLw()) msg.arg2 = 1;
                    try {
                        messenger.send(msg);
                    } catch (RemoteException e) {
                    }
                }
            }

            @Override
            public void onServiceDisconnected(ComponentName name) {}
        };
        if (mContext.bindService(intent, conn, Context.BIND_AUTO_CREATE)) {
            mScreenshotConnection = conn;
            mHandler.postDelayed(mScreenshotTimeout, 10000);
        }
    }
}

這個函數用 AIDL 綁定了 com.android.systemui.screenshot.TakeScreenshotService 服務,注意連接成功時對 msg.arg1、msg.arg2 的賦值,並在 mScreenshotTimeout 裡做了超時處理。再看實現該服務的 TakeScreenshotService:

public class TakeScreenshotService extends Service {
    private static final String TAG = "TakeScreenshotService";
    private static GlobalScreenshot mScreenshot;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    final Messenger callback = msg.replyTo;
                    if (mScreenshot == null) {
                        mScreenshot = new GlobalScreenshot(TakeScreenshotService.this);
                    }
                    mScreenshot.takeScreenshot(new Runnable() {
                        @Override
                        public void run() {
                            Message reply = Message.obtain(null, 1);
                            try {
                                callback.send(reply);
                            } catch (RemoteException e) {
                            }
                        }
                    }, msg.arg1 > 0, msg.arg2 > 0);
            }
        }
    };

    @Override
    public IBinder onBind(Intent intent) {
        return new Messenger(mHandler).getBinder();
    }
}

這裡主要看調用接口:mScreenshot.takeScreenshot() 傳了三個參數,第一個是 runnable,後兩個就是 message 傳來的 arg1、arg2。最後看 GlobalScreenshot.java 裡的 takeScreenshot()(與前面同名但路徑不同):

/**
 * Takes a screenshot of the current display and shows an animation.
 */
void takeScreenshot(Runnable finisher, boolean statusBarVisible, boolean navBarVisible) {
    // 需要把截圖擺正(Surface api 似乎只能按設備自然方向截圖)
    mDisplay.getRealMetrics(mDisplayMetrics);
    float[] dims = { mDisplayMetrics.widthPixels, mDisplayMetrics.heightPixels };
    float degrees = getDegreesForRotation(mDisplay.getRotation());
    boolean requiresRotation = (degrees > 0);
    if (requiresRotation) {
        mDisplayMatrix.reset();
        mDisplayMatrix.preRotate(-degrees);
        mDisplayMatrix.mapPoints(dims);
        dims[0] = Math.abs(dims[0]);
        dims[1] = Math.abs(dims[1]);
    }
    // 截圖
    mScreenBitmap = Surface.screenshot((int) dims[0], (int) dims[1]);
    if (mScreenBitmap == null) {
        notifyScreenshotError(mContext, mNotificationManager);
        finisher.run();
        return;
    }
    if (requiresRotation) {
        Bitmap ss = Bitmap.createBitmap(mDisplayMetrics.widthPixels, mDisplayMetrics.heightPixels, Bitmap.Config.ARGB_8888);
        Canvas c = new Canvas(ss);
        c.translate(ss.getWidth() / 2, ss.getHeight() / 2);
        c.rotate(degrees);
        c.translate(-dims[0] / 2, -dims[1] / 2);
        c.drawBitmap(mScreenBitmap, 0, 0, null);
        c.setBitmap(null);
        mScreenBitmap = ss;
    }
    mScreenBitmap.setHasAlpha(false);
    mScreenBitmap.prepareToDraw();
    startAnimation(finisher, mDisplayMetrics.widthPixels, mDisplayMetrics.heightPixels, statusBarVisible, navBarVisible);
}

這段代碼註釋比較清楚,看到這裡就算真正看到截屏操作了:先獲取屏幕尺寸與旋轉角度,再調用 Surface 的 screenshot 方法截屏保存到 bitmap,把位圖填充到畫布,最後啟動一個延遲的拍照動畫。再往下探究,screenshot 已經是 native 方法:

/**
 * Like {@link #screenshot(int, int, int, int)} but includes all
 * Surfaces in the screenshot.
 *
 * @hide
 */
public static native Bitmap screenshot(int width, int height);

通過 JNI 調到底層,映射的 jni 函數位於 android_view_Surface.cpp,已經是 C++ 層面,統一調用的底層函數是:

static jobject doScreenshot(JNIEnv* env, jobject clazz, jint width, jint height,
        jint minLayer, jint maxLayer, bool allLayers) {
    ScreenshotPixelRef* pixels = new ScreenshotPixelRef(NULL);
    if (pixels->update(width, height, minLayer, maxLayer, allLayers) != NO_ERROR) {
        delete pixels;
        return 0;
    }
    uint32_t w = pixels->getWidth();
    uint32_t h = pixels->getHeight();
    uint32_t s = pixels->getStride();
    uint32_t f = pixels->getFormat();
    ssize_t bpr = s * android::bytesPerPixel(f);
    SkBitmap* bitmap = new SkBitmap();
    bitmap->setConfig(convertPixelFormat(f), w, h, bpr);
    if (f == PIXEL_FORMAT_RGBX_8888) {
        bitmap->setIsOpaque(true);
    }
    if (w > 0 && h > 0) {
        bitmap->setPixelRef(pixels)->unref();
        bitmap->lockPixels();
    } else {
        delete pixels;
        bitmap->setPixels(NULL);
    }
    return GraphicsJNI::createBitmap(env, bitmap, false, NULL);
}

待補充的知識點:Canvas、Bitmap.createBitmap。

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