Converting a view to Bitmap without displaying it in Android?

前端 未结 9 1723
渐次进展
渐次进展 2020-11-22 07:36

I will try to explain what exactly I need to do.

I have 3 separate screens say A,B,C. There is another screen called say HomeScreen where all the 3 screens bitmap sh

9条回答
  •  清酒与你
    2020-11-22 08:08

    I know this may be a stale issue, but I was having problems getting any of these solutions to work for me. Specifically, I found that if any changes were made to the view after it was inflated that those changes would not get incorporated into the rendered bitmap.

    Here's the method which ended up working for my case. With one caveat, however. prior to calling getViewBitmap(View) I inflated my view and asked it to layout with known dimensions. This was needed since my view layout would make it zero height/width until content was placed inside.

    View view = LayoutInflater.from(context).inflate(layoutID, null);
    //Do some stuff to the view, like add an ImageView, etc.
    view.layout(0, 0, width, height);
    
    Bitmap getViewBitmap(View view)
    {
        //Get the dimensions of the view so we can re-layout the view at its current size
        //and create a bitmap of the same size 
        int width = view.getWidth();
        int height = view.getHeight();
    
        int measuredWidth = View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.EXACTLY);
        int measuredHeight = View.MeasureSpec.makeMeasureSpec(height, View.MeasureSpec.EXACTLY);
    
        //Cause the view to re-layout
        view.measure(measuredWidth, measuredHeight);
        view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
    
        //Create a bitmap backed Canvas to draw the view into
        Bitmap b = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas c = new Canvas(b);
    
        //Now that the view is laid out and we have a canvas, ask the view to draw itself into the canvas
        view.draw(c);
    
        return b;
    }
    

    The "magic sauce" for me was found here: https://groups.google.com/forum/#!topic/android-developers/BxIBAOeTA1Q

    Cheers,

    Levi

提交回复
热议问题