In the recent Jetpack Compose update, I discovered...
# compose
s
In the recent Jetpack Compose update, I discovered an intriguing new feature called "GraphicsLayer API". The brief description caught my attention, but unfortunately, there hasn't been an update to the documentation yet. I'm really hoping to find more detailed information beyond just code samples. 👀
Also, the "GraphicsLayer#toImageBitmap" feature is quite interesting too. It's mentioned as a suspend function designed to support rendering contents into a Bitmap, and this is a hardware-accelerated rendering operation. So, I suppose it should be very fast, akin to regular UI drawing, but specifically for creating a hardware-accelerated Bitmap. However, it's unclear whether it should be called on a non-UI coroutine dispatcher. I'm really excited about such developments in Jetpack Compose. Many kudos. 🤗
That's this, right?
Or is it replacing this?
s
Yes, I've been aware of this for a while. However, I was referring specifically to yesterday's Jetpack Compose update, which introduced a new API: 'GraphicsLayer#toImageBitmap'.
j
Interesting thanks
s
Apparently this was also one of the pieces which allowed the resolution of the long awaited and most starred issue for compose so far https://issuetracker.google.com/issues/150812265 I had the exact same feeling as you here Serhii, where it looks super interesting but I was lacking some more samples to get to understand it better. Unfortunately haven’t found more info around it yet. Perhaps looking at how the lazy list
animateItem()
modifier works would work, but it’s definitely not a trivial one to understand 😄
s
The sample in there still does not actually show what the right way to get a hold of a
layer: GraphicsLayer
is 😅 I managed to get something working as I was testing this but I don’t even know if I am doing something wrong 😄
1
a
what the right way to get a hold of a
layer: GraphicsLayer
is
Just use
rememberGraphicsLayer()
.
it's unclear whether it should be called on a non-UI coroutine dispatcher.
All suspend functions in public API should be main-safe, meaning that you can call them with any dispatcher, including the main dispatcher. If they are not, you should probably file a bug. So basically you use it like this:
Copy code
val scope = rememberCoroutineScope()
val graphicsLayer = rememberGraphicsLayer()

ComposableToCapture(
    modifier = modifier.layout { measurable, constraints ->
        val placeable = measurable.measure(constraints)
        layout(placeable.width, placeable.height) {
            placeable.placeWithLayer(0, 0, graphicsLayer)
        }
    }
)

Button(
    onClick = {
        scope.launch {
            val bitmap = graphicsLayer.toImageBitmap()
        }
    }
)
I tried this and it worked well, except that shadows are not drawn to the bitmap.
❤️ 2
160 Views