Android View转Bitmap,并保存为JPG图片

Android View转Bitmap,并保存为JPG图片

前言

项目中需要生成带二维码和一些信息的分享图片,给用户保存到图库。

解决方法

创建View

View view = LayoutInflater.from(this).inflate(R.layout.view_share_month_bill_list, null, false);
// 显示标题
TextView tittle = view.findViewById(R.id.txt_book_name);
tittle.setText("账本:" + billViewModel.getSelectBook().getValue().name);
...
// 合成Bitmap
Bitmap add = BitmapImageUtils.createViewBitmap(view, 1500, 2000);
String str = BitmapImageUtils.saveBitmapToGallery(this, add, "pic_" + DateUtils.getCurTime());
if (null == str) {
    showToast("保存失败!");
} else {
    showToast( "以保存到本地!" + str);
}

View转Bitmap

    /**
     * 生成View的bitmap
     * @param v
     * @param width
     * @param height
     * @return
     */
    public static Bitmap createViewBitmap(View v, int width, int height) {
        //测量使得view指定大小
        int measuredWidth = View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.EXACTLY);
        int measuredHeight = View.MeasureSpec.makeMeasureSpec(height, View.MeasureSpec.EXACTLY);
        v.measure(measuredWidth, measuredHeight);
        //调用layout方法布局后,可以得到view的尺寸大小
        v.layout(0, 0, v.getMeasuredWidth(), v.getMeasuredHeight());
        Bitmap bmp = Bitmap.createBitmap(v.getWidth(), v.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas c = new Canvas(bmp);
        c.drawColor(Color.WHITE);
        v.draw(c);
        return bmp;
    }

bitmap保存到本地

有两种方法,注释掉的方法可以保存到指定文件夹。

    /**
     * 保存图片到图库
     * @param bmp
     * @param bitName
     */
    public static String saveBitmapToGallery(Context context, Bitmap bmp, String bitName) {
        // 系统相册目录
        /*File galleryPath = new File(Environment.getExternalStorageDirectory()
                + File.separator + Environment.DIRECTORY_DCIM
                + File.separator + "Camera" + File.separator);
        if (!galleryPath.exists()) {
            galleryPath.mkdir();
        }

        String fileName = bitName + ".jpg";
        File file = new File(galleryPath, fileName);

        try {
            FileOutputStream fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

        return file.getAbsolutePath();*/

        //插入到系统图库
        return MediaStore.Images.Media.insertImage(context.getContentResolver(), bmp, "菜单", bitName);
    }

完事

发布了103 篇原创文章 · 获赞 31 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/sinat_38184748/article/details/102581262