Without saving to a bitmap, is there a way I can c...
# compose
j
Without saving to a bitmap, is there a way I can cache already-drawn things to a canvas or somehow signal to Compose that it shouldn’t invalidate (trigger a redraw) for a certain composable? I am already using
drawWithCache
which helps with heavy calculations, but I’m doing some pretty resource intensive draw calls in my
drawIntoCanvas
block, and once they’re done they don’t need to be redrawn unless I explicitly tell them to. Code example in 🧵
Copy code
drawWithCache {
    println("drawWithCache") // only called with new state
    // cache certain heavy calculations here
    onDrawBehind {
        drawIntoCanvas { canvas ->
            println("drawIntoCanvas") // this is called constantly
            // many canvas.drawXX calls here
        }
    }
}
One way I thought of is to draw into a bitmap for the first time, then draw that bitmap for subsequent calls using a single
drawImage
call, but I want to know if there’s a way I can rely on the underlying graphics framework to cache it instead because I assume it has more advanced / optimised caching mechanisms?
a
I think adding a
graphicsLayer()
before
drawWithCache()
is the best you can do.
s
When does it get redrawn at this stage already? Is it due to other composables recomposing and this one not skipping? Or does this redraw happen even if there's no recomposition happening?
z
Draws are invalidated by layer, not by composable, so I think graphics layers are the right tool here.
today i learned 1
If merely adding a graphicsLayer modifier doesn’t do the trick, probably using an explicit one with the new APIs would
r
Depends on the layer you use
A regular layer just records the commands for later playback, so that doesn't help when the rasterization step itself is expensive
A graphics layer with an offscreen compositing strategy would however solve this. The commands are rasterized into a GPU texture that gets reused across frames and that's super cheap to draw (at the cost of memory and in some cases bandwidth)
j
thank you all for the suggestions, I found some time to get back to this today and using the offscreen strategy for the required layer gives me the exact behaviour I’m after 🎉
🎉 1