Is there anyway of saving a composable to a `Bitma...
# compose
r
Is there anyway of saving a composable to a
Bitmap
Just like what we do with
View.drawToBitmap()
p
I have not see it yet, but you can try to use the ComposeView with your composables inside and use the drawToBitmap() on that. I would assume that would work.
r
That only worked when I set the
ComposeView
as the content of my Activity/Fragment. I haven't had any success manually inflating a
ComposeView
in isolation
p
Does a View.drawToBitmap() work when the View is in isolation?
r
This error is when I try to manually inflate and layout the composable using a
ComposeView
@Peter Fortuin Yes it works for regular views. You just have to call layout on it
p
Ok.
r
@Nader Jawad Any help here?
n
View.drawToBitmap won't work for hardware accelerated canvases. Similarly compose would have similar limitations. What is the use case for drawing a composable to a Bitmap? There might be some alternatives to accomplish the same goal
r
@Nader Jawad I'm drawing some items on a canvas and would like to save it to a bitmap
n
In this case I would recommend creating an ImageAsset and creating a Canvas with that assert to draw content into the bitmp directly
Some sample code would look like the following. This will create a DrawScope that you can issue the same drawing commands that would be issued from a draw modifier:
Copy code
fun drawToImageAsset() {
    val density = Density(1.0f)
    val width = 100
    val height = 100
    val canvas = Canvas(ImageAsset(width, height))
    val size = Size(width.toFloat(), height.toFloat()) 
    CanvasDrawScope().draw(density, LayoutDirection.Ltr, canvas, size) {
        drawRect(Color.Red)
    }
    // Code to save ImageAsset to file
}
r
Take something like this for instance, each shape is a separate composable which contains a
Canvas
wrapped inside a
Box
so that I can add
Modifier.dragGestureFilter
and
Modifier.tapGestureFilter
to each individual item separately.
n
We don't expose a way to get a handle to the composable itself as per the react development model, It might work to issue drawing commands directly to the backing ImageAsset and display that on screen via
Image
composable instead of trying to output the composable content to a bitmap
r
Thank you for the info. I'll make the necessary adjustments.
n
We have some testing facilities to output composables to Bitmaps but they rely on APIs introduced in Android O
So that also might be an alternative depending on the API level you are targeting
r
I'm playing around with graphics in compose so API levels won't matter
n
@Filip Pavlis is there a way to access the Semantics API
captureToImage
from outside ComposeTestRule?
1
f
Nope, we didn't invest in making these APIs to work outside of the testing framework.
1