布局xml转bitmap

代码:

        //获取屏幕大小
        DisplayMetrics dm = activity.getResources().getDisplayMetrics();
        int newWidth = dm.widthPixels;
        int newHeight = dm.heightPixels;

        View view = activity.getLayoutInflater().inflate(R.layout.cs_screenshot, null);

        //打开图像缓存
        view.setDrawingCacheEnabled(true);
         //必须调用measure和layout方法才能成功保存可视组件的截图到png图像文件
        //测量View大小(这样能保证测量的和实际显示的大小一致,720/1280为屏幕大小, 
                  MeasureSpec.AT_MOST/EXACTLY允许view的最大大小/精确大小)
        view.measure(View.MeasureSpec.makeMeasureSpec(720, View.MeasureSpec.EXACTLY),
                View.MeasureSpec.makeMeasureSpec(1280, View.MeasureSpec.EXACTLY));
        //不能全屏(和真实显示大小不一致)
        //view.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
       //         View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
        try {
            //获得可视组件的截图
            Bitmap bitmap = view.getDrawingCache();
            //将截图保存在SD卡根目录的test.png图像文件中
            String sdcardPath = getSDCardPath(activity);
            String fileName = getFileName() + ".png";
            String filePath = sdcardPath + "/" + fileName;
            FileOutputStream fos = new FileOutputStream(filePath);
            //将Bitmap对象中的图像数据压缩成png格式的图像数据,并将这些数据保存在test.png文件中
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
            //关闭文件输出流
            fos.close();
            //上面的步骤已经把xml转成bitmap保存到filePath中
            //插入到相册通知图库更新
             File file = new File(filePath);
            try {
                MediaStore.Images.Media.insertImage(activity.getContentResolver(),
                        file.getAbsolutePath(), fileName, null);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            // 最后通知图库更新
            activity.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + Environment.getExternalStorageDirectory().getPath())));
            Log.d("tag", "通知成功");
          }
          catch (Exception e) {
            Log.e("tag", "保存出错:" + e.toString());
        }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值