Converting a view to Bitmap without displaying it in Android?

前端 未结 9 1878
渐次进展
渐次进展 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:09

    there is a way to do this. you have to create a Bitmap and a Canvas and call view.draw(canvas);

    here is the code:

    public static Bitmap loadBitmapFromView(View v) {
        Bitmap b = Bitmap.createBitmap( v.getLayoutParams().width, v.getLayoutParams().height, Bitmap.Config.ARGB_8888);                
        Canvas c = new Canvas(b);
        v.layout(v.getLeft(), v.getTop(), v.getRight(), v.getBottom());
        v.draw(c);
        return b;
    }
    

    if the view wasn't displayed before the size of it will be zero. Its possible to measure it like this:

    if (v.getMeasuredHeight() <= 0) {
        v.measure(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        Bitmap b = Bitmap.createBitmap(v.getMeasuredWidth(), v.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
        Canvas c = new Canvas(b);
        v.layout(0, 0, v.getMeasuredWidth(), v.getMeasuredHeight());
        v.draw(c);
        return b;
    }
    

    EDIT: according to this post, Passing WRAP_CONTENT as value to makeMeasureSpec() doesn't to do any good (although for some view classes it does work), and the recommended method is:

    // Either this
    int specWidth = MeasureSpec.makeMeasureSpec(parentWidth, MeasureSpec.AT_MOST);
    // Or this
    int specWidth = MeasureSpec.makeMeasureSpec(0 /* any */, MeasureSpec.UNSPECIFIED);
    view.measure(specWidth, specWidth);
    int questionWidth = view.getMeasuredWidth();
    

提交回复
热议问题