Android--将布局保存成图像


//将布局转换为View类型对象
  View view = getLayoutInflater().inflate(R.layout.main, null);
  //打开图像缓存
  view.setDrawingCacheEnabled(true);
  //必须调用measure和layout方法才能成功保存可视组件的截图到png图像文件
  //测量View大小
  view.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
    MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
  //发送位置和尺寸到View及其所有的子View
  view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
  try{
   //获得可视组件的截图
   Bitmap bitmap = view.getDrawingCache();
   //将截图保存在SD卡根目录的test.png图像文件中
   FileOutputStream fos = new FileOutputStream("/sdcard/test.png");
   //将Bitmap对象中的图像数据压缩成png格式的图像数据,并将这些数据保存在test.png文件中
   bitmap.compress(CompressFormat.PNG, 100, fos);
   //关闭文件输出流
   fos.close();
  }catch (Exception e) {
   
  }

相关内容