Reputation: 778
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
Upvotes: 4
Views: 305
Reputation: 778
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!
Upvotes: 1
Reputation: 373
Maybe these views are H/W accelerated. Try using PixelCopy instead.
Upvotes: 0