【问题标题】:Convert prepared layout to bitmap and save as image in file将准备好的布局转换为位图并保存为文件中的图像
【发布时间】:2015-10-02 13:20:35
【问题描述】:

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

目前我已经尝试获取布局、启用绘图缓存、传递到位图并保存在文件中

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);}

【问题讨论】:

标签: android file view bitmap


【解决方案1】:

如果有人遇到同样的问题。这解决了我的问题。我只需要在 Activity 中创建后获取 Layout

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);

【讨论】:

    猜你喜欢
    • 2015-11-03
    • 2014-03-10
    • 2019-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-17
    相关资源
    最近更新 更多