【发布时间】:2022-12-16 07:42:52
【问题描述】:
使用经典的Views 时,很容易从视图中获取位图而不显示它。我通过 LayoutInflater 创建视图类,然后,由于它没有附加到视图,我先测量它。
我有以下扩展函数来测量它并在位图上绘制视图:
fun View.toBitmap(width, height): Bitmap {
this.measure(
View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.EXACTLY),
View.MeasureSpec.makeMeasureSpec(height, View.MeasureSpec.EXACTLY),
)
val bitmap = Bitmap.createBitmap(this.measuredWidth, this.measuredHeight, Bitmap.Config.ARGB_8888)
val canvas = Canvas(bitmap)
this.layout(0, 0, this.measuredWidth, this.measuredHeight)
this.draw(canvas)
return bitmap
}
使用Composables 时,我无法从视图中成功导出位图。
我想象这样的事情:
class MyComposableView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
): AbstractComposeView(context, attrs, defStyleAttr) {
@Composable
override fun Content() {
MyComposable()
}
}
我所做的是用应用程序上下文实例化一个MyComposableView,然后我尝试获取一个带有扩展函数toBitmap的位图。
结果是以下异常:
java.lang.IllegalStateException: Cannot locate windowRecomposer; View io.myapp.MyComposableView{f66ecdd V.E...... ......I. 0,0-0,0} is not attached to a window
我不明白的是为什么为 AbstractComposeView 抛出异常,但没有为通过 inflater 获得的视图抛出异常。
编辑: 2022 年 4 月 9 日,除了使用经典的 XML 布局之外,似乎没有其他解决方案。
【问题讨论】:
标签: android bitmap composable