使用 classicView
时,很容易从视图中获取位图而不显示它。我通过 a 创建视图类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
s 时,我无法成功从视图中导出位图。
我想象过这样的事情:
class MyComposableView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
): AbstractComposeView(context, attrs, defStyleAttr) {
@Composable
override fun Content() {
MyComposable()
}
}
我所做的是MyComposableView
使用应用程序上下文实例化 a,然后我尝试使用扩展函数获取位图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
通过充气机获得的视图抛出异常但不抛出异常。