将准备好的布局转换为位图并保存为文件中的图像



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

现在我已经尝试得到我的布局,启用绘图缓存,传递到位图和保存在文件

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

中创建布局
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);

最新更新