在使用经典的 View
时,很容易从视图中获取位图而无需显示它。我通过 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
}
当我使用
Composable
时,我无法从视图中导出位图。我想象的是这样的:
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
中会抛出异常。
编辑:截至2022年4月9日,似乎除使用传统XML布局外,没有其他解决方案。