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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章