《第二行代码进阶》 以View显示的内容作为图下载到本地
2021-09-06 本文已影响0人
你的益达233
关键代码:
/**
* @desc : 将View转化为图片并保存到本地
* @author : congge on 2021-09-02 16:42
**/
public static void viewSaveToImage(View view, String pathDir, String imageName, String toastMsg) {
view.setDrawingCacheEnabled(true);
view.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
view.setDrawingCacheBackgroundColor(Color.WHITE);
// 把一个View转换成图片,并保存
saveImage(view.getContext(),loadBitmapFromView(view),pathDir,imageName,toastMsg);
view.destroyDrawingCache();
}
private static Bitmap loadBitmapFromView(View v) {
int w = v.getWidth();
int h = v.getHeight();
Bitmap bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(bmp);
c.drawColor(Color.WHITE);
/** 如果不设置canvas画布为白色,则生成透明 */
v.layout(0, 0, w, h);
v.draw(c);
return bmp;
}
保存bitamp到本地
public static void saveImage(Context context, Bitmap bitmap, String pathDir, String imageName, String toastMsg) {
if (bitmap != null) {
File file = new File(pathDir);
FileOutputStream fileOutputStream = null;
//文件夹不存在,则创建它,只是创建wx文件夹
if (!file.exists()) {
file.mkdir();
}
try {
String path = pathDir + "/" + imageName + ".jpg";
fileOutputStream = new FileOutputStream(path);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream);
fileOutputStream.close();
if (!TextUtils.isEmpty(toastMsg)) {
ToastUtils.show(toastMsg);
}
//wx下载
//更新图库
MediaScannerConnection.scanFile(
context,
new String[]{path},
null, null);
} catch (Exception e) {
e.printStackTrace();
}
}
}