[FIXED] Convert layout to bitmap?

Issue

How do I convert the following layout to a bitmap?

I tried using Kotlin’s view.drawToBitmap() but it only applies to views and not layouts.

            <LinearLayout
                android:id="@+id/layout"
                android:layout_width="200dp"
                android:layout_height="wrap_content"
                android:orientation="vertical">

            <TextView
                android:id="@+id/tv1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"/>

            <TextView
                android:id="@+id/tv2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />

            </LinearLayout>

Solution

Pass your view into viewToBitmap(view)

private Bitmap viewToBitmap(LinearLayout view) {
            try {
               // create bitmap screen capture
                view.setDrawingCacheEnabled(true);
                Bitmap bitmap = Bitmap.createBitmap(view.getDrawingCache());
                view.setDrawingCacheEnabled(false);
                return bitmap;
            } catch (Throwable e) {
                e.printStackTrace();
                Log.e(TAG, "takeScreenshot: Throwable: "+e.getMessage() );
                return null;
            }
        }

Answered By – Sneh Malani

Answer Checked By – Marilyn (Easybugfix Volunteer)

Leave a Reply

(*) Required, Your email will not be published