view生成图片并保存在本地

作者: 选一个昵称这么难 | 来源:发表于2017-10-23 17:25 被阅读548次

    实现效果:

    效果图

    实现以上功能只需要两步:
    一:view生成截图
    这个布局的整体是一个scrollview,具体布局我就不贴出来了,我们需要的截图不是把屏幕上的内容显示出来而是要显示整个view的内容,我试了一些办法,要么截的图不全,要么返回的是null,下面列举我项目中用到的方法

    private Bitmap getViewBitmap(ScrollView scrollView) {
            int h = 0;
            Bitmap bitmap;
            // 获取scrollView实际高度,这里很重要
            for (int i = 0; i < scrollView.getChildCount(); i++) {
                h += scrollView.getChildAt(i).getHeight();
            }
            // 创建对应大小的bitmap
            bitmap = Bitmap.createBitmap(scrollView.getWidth(), h,
                    Bitmap.Config.ARGB_8888);
            final Canvas canvas = new Canvas(bitmap);
            scrollView.draw(canvas);
            return bitmap;
        }
    

    当然如果你的布局是其他的布局,比如线性布局或者listview,原理都是一样的
    二:保存在本地
    也就是把bitmap保存成file

       private void saveImg() {
          //把图片存储在哪个文件夹
           File file = new File(Environment.getExternalStorageDirectory(), "maozhua");
            if (!file.exists()) {
                file.mkdir();
            }
          //图片的名称
            String name = "mz.jpg";
            File file1 = new File(file, name);
            if (!file1.exists()){
                try {
                    FileOutputStream fileOutputStream = new FileOutputStream(file1);
        //这个100表示压缩比,100说明不压缩,90说明压缩到原来的90%
        //注意:这是对于占用存储空间而言,不是说占用内存的大小                bitmap.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream);
                    fileOutputStream.flush();
                    fileOutputStream.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        //通知图库即使更新,否则不能看到图片
            getActivity().sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + file1.getAbsolutePath())));
        }
    

    THAT IS ALL!

    相关文章

      网友评论

        本文标题:view生成图片并保存在本地

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