Android獲取當前佈局視圖的截屏

目前在做項目截屏採用的是取View的cacheDrawable 來實現截屏,能得到bitmap然後通過將bitmap轉換成file進行保存.比如我一個RelativeLayout佈局,我要獲取這佈局所有的字view然後截屏,可以這樣寫:

        contentLayout.setDrawingCacheEnabled(true);
        contentLayout.buildDrawingCache();
        Bitmap bitmap = Bitmap.createBitmap(contentLayout.getDrawingCache());
        if (bitmap != null) {
            saveImageToGallery(bitmap);
        }

當然先獲取權限,在進行文件流的讀寫:

    public boolean saveImageToGallery(Bitmap bmp) {
        // 首先保存圖片
        String path = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "screenshot";
        File appDir = new File(path);
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        String fileName = System.currentTimeMillis() + ".jpg";
        File file = new File(appDir, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            //通過io流的方式來壓縮保存圖片
            boolean isSuccess = bmp.compress(Bitmap.CompressFormat.JPEG, 60, fos);
            fos.flush();
            fos.close();
            //保存圖片後發送廣播通知更新數據庫
            storePath = file.getAbsolutePath();
            Uri uri = Uri.fromFile(file);
            sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
            if (isSuccess) {
                return true;
            } else {
                return false;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

這個方式的問題就是不能截取到狀態欄整個屏幕,後面我看github也有其他的庫可以截取到整個屏幕通過一個service
:

https://github.com/BruceWind/AndroidScreenShot_SysApi
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章