I am trying to use a Preview to display a Composab...
# compose-android
e
I am trying to use a Preview to display a Composable that I am converting to a Bitmap, doing something like this:
Copy code
val fakeCanvas = Canvas()
val composeView =
    ComposeView(parent.context)
        .apply {
            layoutParams = ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT,
            )
            setParentCompositionContext(compositionContext)
            setContent(content)
        }
        .also(parent::addView)

composeView.draw(fakeCanvas)

composeView.measure(measureSpec, measureSpec)
At this point,
composeView.measureWidth
or
measuredHeight
is zero. This only happens during the Preview, not when I am using the Composable itself. What happens differently during the preview process?
r
You are measuring the view after drawing it. First measure and layout, then draw
e
Thanks Romain. That seems to be a problem, but after changing it, the Preview keeps failing, and the Composable working. So, after this being fixed (was it inducing performance issues? not sure) the stated problem seems still to be an issue.
r
What do you do with the Canvas? It has no backing surface
e
This method returns a BitmapDescriptor:
Copy code
composeView.draw(fakeCanvas)

composeView.measure(measureSpec, measureSpec)

// Here I see the size is already for width and height

composeView.layout(0, 0, composeView.measuredWidth, composeView.measuredHeight)

val bitmap =
    Bitmap
        .createBitmap(
            composeView.measuredWidth,
            composeView.measuredHeight,
            Bitmap.Config.ARGB_8888,
        )
bitmap.applyCanvas { composeView.draw(this) }
parent.removeView(composeView)

return BitmapDescriptorFactory.fromBitmap(bitmap)
r
You can remove the first draw at the top
Also your fake Canvas is unnecessary since applyCanvas creates one
Anyway I don't know what BitmapDescriptor is but that might be your problem. The Preview mode is not a full implementation of Android
e
Thanks Romain. Could that have lead (the fake canvas and wrong order) to performance issues instead? BitmapDescriptor is a Maps SDK class, that can be used for Custom Markers.
r
Drawing twice definitely won't help performance
And yeah I wouldn't be surprised if the maps SDK doesn't (fully) work in preview
Also remember that doing what you're doing means you are using the CPU to render the composable
e
> Also remember that doing what you’re doing means you are using the CPU to render the composable Is that because of the Canvas usage? What would be a better approach?
r
It’s because you are rendering into a software. It is possible to use the GPU to render into a hardware bitmap but unless you are running into major performance issues I wouldn’t worry about it.