简体   繁体   中英

Draw a fragments view on a canvas

I am trying to draw the view of a fragment onto a canvas to export it as a image. I tried following this querstion: Android: Draw a view on canvas and managed to draw a inflated view onto a canvas, but when I try to draw the fragments view onto it, it messes up the layout.

This is my fragment host:

<FrameLayout
        android:layout_width="1000px"
        android:layout_height="1000px"
        android:visibility="invisible"
        tools:ignore="PxUsage"
        android:id="@+id/fragment_host"/>

This is how I draw on my canvas

supportFragmentManager.beginTransaction()
        .replace(R.id.fragment_host, MyTrackViewerFragment().apply {
            onCreateControls = {

                bitmap = Bitmap.createBitmap(1000, 1000, Bitmap.Config.ARGB_8888)
                val canvas = Canvas(bitmap)

                it.apply {
                    layoutParams = LinearLayout.LayoutParams(1000, 1000)
                    measure(measuredWidth, measuredHeight)
                    layout(0, 0, 1000, 1000)
                    draw(canvas)
                }

                findViewById<ImageView>(R.id.preview).setImageBitmap(bitmap)
                ImageView.ScaleType.CENTER_CROP
                supportFragmentManager.beginTransaction().remove(this).commit()
            }
        })
        .commit()

This is the result (the black square is the preview image view):

The fragment in the fragment host draws correcly, also after calling the measure and layout method.

A different fragment gives similiar results (the square is the preview image view):

What am I missing?

EDIT: It seems like layout(0, 0, 1000, 1000) messes up the layout, but I can't find why

Figured out the issue came with the RelativeLayout and use of match_parent or wrap_content . It looks like it did not layout properly and thus the view looked somehow correct in the Fragment but not when measuring it manually.

By wrapping the RelativeLayout inside of a LinearLayout and giving misaligned elements a fixed size (px or dp) it finally worked!

Maybe these views are H/W accelerated. Try using PixelCopy instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM