[英]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.我正在尝试将片段的视图绘制到 canvas 上以将其导出为图像。 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.我尝试按照以下问题进行操作: Android: Draw a view on canvas并设法在 canvas 上绘制了一个膨胀视图,但是当我尝试将其绘制到布局上时,它会将视图碎片化。
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这就是我在 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.在调用 measure 和 layout 方法之后,fragment host 中的 fragment 也可以正确绘制。
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编辑:似乎layout(0, 0, 1000, 1000)
弄乱了布局,但我找不到原因
Figured out the issue came with the RelativeLayout
and use of match_parent
or wrap_content
.发现问题与RelativeLayout
和match_parent
或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!通过将 RelativeLayout 包装在 LinearLayout 中并为未对齐的元素提供固定大小(px 或 dp),它终于奏效了!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.