将linlayout布局转为bitmap图片和保存

时间:2022-02-24 05:21:13

1.首先新建路径

 File filedirs = new File(Environment.getExternalStorageDirectory(), "/YuLin/");
if (!filedirs.exists()) {
filedirs.mkdirs();
}

2.生成某个布局的bitmap

    /**
* 生成某个LinearLayout的图片
*/
private Bitmap getLinearLayoutBitmap2(LinearLayout linearLayout, int screenWidth, int screenHeight) {
int w = screenWidth;
int h = screenHeight ;
// 创建对应大小的bitmap
linearLayout.measure(0, 0);
Bitmap bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
canvas.drawColor(Color.WHITE);
linearLayout.draw(canvas);
return bitmap;
}

3.把bitmap保存为文件

 Bitmap btp = getLinearLayoutBitmap2(lin_share, lin_share.getWidth(),
lin_share.getHeight());
File file = new File(filedirs, getTimeStamp() + ".jpg");

4.保存文件到手机

 saveBitmap2(file, btp,99);
/**
* 保存方法
*/
private boolean saveBitmap(File mFile, Bitmap bm) {
if (mFile.exists()) {
mFile.delete();
mFile.mkdirs();
}
try {
FileOutputStream out = new FileOutputStream(mFile);
bm.compress(Bitmap.CompressFormat.JPEG, 40, out);
out.flush();
out.close();
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
} }

注意 不懂得用法 查看下方完整方法

    public File saveSharePic(LinearLayout lin_share) {
File filedirs = new File(Environment.getExternalStorageDirectory(), "/YuLin/");
if (!filedirs.exists()) {
filedirs.mkdirs();
}
Bitmap btp = getLinearLayoutBitmap2(lin_share, lin_share.getWidth(),
lin_share.getHeight());
File file = new File(filedirs, getTimeStamp() + ".jpg");
try {
saveBitmap2(file, btp,99);
} catch (Exception e) {
e.printStackTrace();
}
return file;
}

by:leileitua