例如:将NestedScrollView视图(继承ViewGroup类)生成Bitmap
private Bitmap getBitmapByView(NestedScrollView scrollView) {
int h = 0;
Bitmap bitmap = null;
// 获取scrollview实际高度
for (int i = 0; i < scrollView.getChildCount(); i++) {
h += scrollView.getChildAt(i).getHeight();//获取scrollView的屏幕高度
scrollView.getChildAt(i).setBackgroundColor(
Color.parseColor("#ffffff"));
}
// 创建对应大小的bitmap
bitmap = Bitmap.createBitmap(scrollView.getWidth(), h,
Bitmap.Config.RGB_565);
final Canvas canvas = new Canvas(bitmap);//把创建的bitmap放到画布中去
scrollView.draw(canvas);//绘制canvas 画布
return bitmap;
}
保存图片
public void savePicture(Bitmap bm, String fileName) {
LogUtils.d("正在生成文件.........");
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/inform";
File file = new File(path);
if (FileUtils.isFileExists(file)) {
FileUtils.delete(file);
file.mkdirs();
} else {
// 创建文件夹
file.mkdirs();
}
File myCaptureFile = new File(path + "/" + fileName);
LogUtils.d("myCaptureFile", myCaptureFile.getAbsoluteFile());
if (FileUtils.isFileExists(myCaptureFile)) {
// 删除已存在的文件
FileUtils.delete(myCaptureFile);
}
try {
myCaptureFile.createNewFile();
//重新创建文件
LogUtils.d("CaptureFileName", myCaptureFile.getAbsoluteFile());
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
//压缩保存到本地
bm.compress(Bitmap.CompressFormat.JPEG, 95, bos);
bos.flush();
bos.close();
// ------------- 获取图片的宽高 -----------------
int[] wh = ImageUtils.getSize(myCaptureFile);
LogUtils.d("宽:" + wh[0], "高:" + wh[1]);
// Toast.makeText(this, "保存成功!", Toast.LENGTH_SHORT).show();
LogUtils.d("保存成功");
} catch (Exception e) {
LogUtils.e(e);
Toast.makeText(this, "保存失败!", Toast.LENGTH_SHORT).show();
}
}