美文网首页简化开发Android开发
《第二行代码进阶》 以View显示的内容作为图下载到本地

《第二行代码进阶》 以View显示的内容作为图下载到本地

作者: 你的益达233 | 来源:发表于2021-09-06 17:05 被阅读0次

关键代码:

 /**
 * @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();
        }

    }

}

相关文章

网友评论

    本文标题:《第二行代码进阶》 以View显示的内容作为图下载到本地

    本文链接:https://www.haomeiwen.com/subject/faxywltx.html