代码:
//获取屏幕大小
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());
}