前言

需要:将自己发布的内容绘成一张图片,然后保存到本地。

因为之前做过uni-app的这个导出的功能,所以一开始想的也是通过创建一个空白的画布(canvas),在上面描绘出需要的内容。经历了两天的痛苦的挣扎。。。加上我看了一些其他人开发这个功能的一些思路和想法,我果断的放弃了通过canvas来绘制。新的想法是通过Layout布局创建一个xml文件,在布局里添加上确定的控件信息,像图片这种不确定的信息就暂时不添加,直接通过代码动态生成。然后将xml文件转换成Bitmap,再将他保存到本地

将xml布局转换成Bitmap

1
2
3
4
5
6
7
8
9
10
11
12
13
public static Bitmap getBitmapByView(ScrollView scrollView) {
int h = 0;
Bitmap bitmap = null;
for (int i = 0; i < scrollView.getChildCount(); i++) {
h += scrollView.getChildAt(i).getHeight();
}
bitmap = Bitmap.createBitmap(scrollView.getWidth(), h,
Bitmap.Config.RGB_565);
final Canvas canvas = new Canvas(bitmap);
canvas.drawColor(Color.WHITE);
scrollView.draw(canvas);
return bitmap;
}

保存到本地

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
 //保存地址
private static final String SD_PATH = "/sdcard/dskqxt/pic/";
private static final String IN_PATH = "/dskqxt/pic/";

public static String saveBitmap(Context context, Bitmap mBitmap) {
String savePath;
File filePic;
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
savePath = SD_PATH;
} else {
savePath = context.getApplicationContext().getFilesDir()
.getAbsolutePath()
+ IN_PATH;
}
try {
filePic = new File(savePath + generateFileName() + ".jpg");//保存的格式为jpg
if (!filePic.exists()) {
filePic.getParentFile().mkdirs();
filePic.createNewFile();
}
FileOutputStream fos = new FileOutputStream(filePic);
mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
//插入系统相册
MediaStore.Images.Media.insertImage(context.getContentResolver(), filePic.getAbsolutePath(), savePath, "团纸日记图片集");
//Uri uri = Uri.fromFile(new File(savePath));
Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
//intent.setData(uri);
context.sendBroadcast(intent);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}

return filePic.getAbsolutePath();
}

动态生成图片控件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
canvas_images.removeAllViews();
for(int i = 0; i < articleInfo.getImages().size(); i++){
ImageView imageView = new ImageView(this);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
//imageView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
layoutParams.setMargins(0, 15, 0, 0);
//layoutParams.height = 1200;
//layoutParams.width = 900;
imageView.setLayoutParams(layoutParams);
imageView.setMaxHeight(1500);
imageView.setMaxWidth(900);
imageView.setAdjustViewBounds(true);
Glide.with(mContext).load(articleInfo.getImages().get(i)).into(imageView);
canvas_images.addView(imageView);
}