将准备好的布局转换为位图并将其另存为文件中的图像 [英] Convert prepared layout to bitmap and save as image in file

查看:143
本文介绍了将准备好的布局转换为位图并将其另存为文件中的图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将准备好的布局保存到外部存储器中的图像文件中

I need to save my prepared layout to image file in external memory

目前,我尝试获取布局,启用图形缓存,传递给位图并保存在文件中

For now I've tried to get my layout, enable drawing cache, pass to bitmap and save in file

LayoutInflater inflate = LayoutInflater.from(this);
    View view = inflate.inflate(R.layout.to_send, null);
    view.setDrawingCacheEnabled(true);
    Bitmap returnedBitmap;
    if (view.getMeasuredHeight() <= 0) {
        view.measure(ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT);
        returnedBitmap = Bitmap.createBitmap(view.getMeasuredWidth(), view.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
        returnedBitmap.recycle();
        Canvas c = new Canvas(returnedBitmap);
        view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
        view.draw(c);
    }
    else {
        returnedBitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(returnedBitmap);
        Drawable bgDrawable = view.getBackground();
        if (bgDrawable != null)
            bgDrawable.draw(canvas);
        else
            canvas.drawColor(Color.WHITE);
        view.draw(canvas);
    }
    //Bitmap bitmap = content.getDrawingCache();
    File fPath = Environment.getExternalStorageDirectory();
    File f = new File(fPath + "Send.png");
    try {
        if (!f.exists()) {
            f.createNewFile();
        }
        FileOutputStream strm = new FileOutputStream(f);
        returnedBitmap.compress(Bitmap.CompressFormat.PNG, 80, strm);
        strm.close();
        //content.invalidate();
    }
    catch (Exception e){
        e.printStackTrace();
    } finally {
        view.setDrawingCacheEnabled(false);}

推荐答案

如果有人遇到相同的问题.这里解决了我的问题.在Activity中创建布局后,我只需要获取

In case if somebody meets the same problem. Here what solved my problem. I just needed to get Layout after it was created in Activity

RelativeLayout shareLayout = (RelativeLayout) getActivity().findViewById(R.id.loveSpace);
shareLayout.setDrawingCacheEnabled(true);
shareLayout.buildDrawingCache();
Bitmap bm = shareLayout.getDrawingCache();
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, bytes);

这篇关于将准备好的布局转换为位图并将其另存为文件中的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆