例如:将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();
}
}