美文网首页
Android 提取指定View内容保存到指定目录

Android 提取指定View内容保存到指定目录

作者: Kevin_Gao | 来源:发表于2018-07-17 16:13 被阅读0次

    1.首先在AndroidManifest.xml中申请权限

        <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
        <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
    

    2.截取指定View的内容

       public Bitmap viewShot() {
            //获取window最底层的view,这里我们指定为截取DecorView
            View view = getWindow().getDecorView();
            view.buildDrawingCache();
    
            //状态栏高度
            Rect rect = new Rect();
            view.getWindowVisibleDisplayFrame(rect);
            int stateBarHeight = rect.top;
            Display display = getWindowManager().getDefaultDisplay();
    
            //获取屏幕宽高
            int widths = display.getWidth();
            int height = display.getHeight();
    
            //设置允许当前窗口保存缓存信息
            view.setDrawingCacheEnabled(true);
    
            //去掉状态栏高度
            Bitmap bitmap = Bitmap.createBitmap(view.getDrawingCache(), 0, stateBarHeight, widths, height - stateBarHeight);
    
            view.destroyDrawingCache();
            return bitmap;
        }
    

    3.将Bitmap保存到指定目录

        public static void saveImage(Bitmap bmp) {
            File appDir = new File(Environment.getExternalStorageDirectory(), "Boohee");
            if (!appDir.exists()) {
                appDir.mkdir();
            }
            String fileName = System.currentTimeMillis() + ".png";
            File file = new File(appDir, fileName);
            try {
                FileOutputStream fos = new FileOutputStream(file);
                bmp.compress(Bitmap.CompressFormat.PNG, 100, fos);
                fos.flush();
                fos.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    
    

    扩展

    1.Drawable ----> Bitmap

    BitmapDrawable bd = (BitmapDrawable) drawable;
    Bitmap bm= bd.getBitmap();
    

    2.Bitmap--------> Drawable:
    第一种:

    Drawable drawable = new BitmapDrawable(bitmap); 
    

    第二种:

    BitmapDrawable bd= new BitmapDrawable(getResource(), bm);
    

    相关文章

      网友评论

          本文标题:Android 提取指定View内容保存到指定目录

          本文链接:https://www.haomeiwen.com/subject/futgpftx.html