Landry Norris
08/29/2022, 7:48 PMLandry Norris
08/29/2022, 7:51 PM@Composable
fun MyCustomView(pixels: IntArray, someVariable: Int) {
Canvas() {
val bitmap = Bitmap.createBitmap(size.width.toInt(), size.height.toInt(),
Bitmap.Config.ARGB_8888)
bitmap.copyPixelsFromBuffer(IntBuffer.wrap(pixels))
drawIntoCanvas { canvas ->
someVariable //meaningless read to force recomposition
val native = canvas.nativeCanvas
native.drawBitmap(bitmap, 0f, 0f, paint.asFrameworkPaint())
}
}
}
I’d like to be able to apply Modifier.id(someVariable) or something to indicate that pixels depends on someVariable.ryan.fonzi
08/29/2022, 7:58 PMval bitmap = remember(someVariable) { ... }
do what you want?Zach Klippenstein (he/him) [MOD]
08/29/2022, 8:00 PMLandry Norris
08/29/2022, 8:01 PMLandry Norris
08/29/2022, 8:06 PMLandry Norris
08/29/2022, 8:07 PMryan.fonzi
08/29/2022, 8:09 PMsomeVariable
changes, then either should work. It doesn't matter how many additional reads you do in the calculation block, the only things that cause recalculation are what you pass in for the key
.Landry Norris
08/29/2022, 8:12 PMryan.fonzi
08/29/2022, 8:17 PMremember
, but the same concept applies to the key()
function.ryan.fonzi
08/29/2022, 8:18 PMLandry Norris
08/29/2022, 8:19 PMval bitmap = remember(someVariable) { Bitmap.createBitmap(size.width.toInt() }
to get a state read of someVariable along with a comment explaining why I don’t use the value in the remember block.Landry Norris
08/29/2022, 8:21 PMZach Klippenstein (he/him) [MOD]
08/29/2022, 8:31 PMrememberUpdatedState
+ `drawWithCache`:
val updatedSomeVariable by rememberUpdatedState(someVariable)
Box(Modifier.drawWithCache {
val bitmap = createBitmap(updatedSomeVariable…)
onDrawBehind {
// draw code here
}
}
That’s really only useful if you’re also reading other state that can change independently from composition, since it wouldn’t require always recomposing to re-draw.