I need to draw the exact same icon several times - I'm currently using
Canvas
+
drawPath
. Is there a legit way to optimize the whole thing? My idea was to save the `Path`(s) using
staticCompositionLocalOf
. More in thread
ste
05/05/2021, 8:15 AM
Basic implementation
Copy code
@Composable
fun MyIcon() {
Canvas(modifier = Modifier.size(size = 50.dp)) {
drawPath(Path().apply {
// non expensive calculus, but they are repeated every time
}, color = Color.Red)
}
}
ste
05/05/2021, 8:17 AM
So, given that the
Path
is created every time (but it's always the same), does make sense to store it somewhere (e.g using
staticCompositionLocalOf
)? There will be a performance gain?
ste
05/05/2021, 8:20 AM
How it would look like
Copy code
@Composable
fun MyIcon() {
val path = LocalMyIconPath.current
Canvas(modifier = Modifier.size(size = 50.dp)) {
drawPath(path, color = Color.Red)
}
}
n
nitrog42
05/05/2021, 8:21 AM
hmm there is a modifier that I like that is called drawWithCache :
but with a Canvas I don't think it's the way, and storing in a state might be wrong if the size change for any reason (I do understand that it shouldn't)
s
ste
05/05/2021, 8:24 AM
@nitrog42 Yup I didn't mention that I'll also use
CompositionLocalProvider
, so it shouldn't be a problem if the size changes, because the path would be rebuilt as well
ste
05/05/2021, 8:25 AM
I guess
drawWithCache
is fine if I need to draw just once (one icon).
Alternatively, I could just remember the
Modifier.drawWithCache
and reuse it
a
Albert Chang
05/06/2021, 12:36 AM
Using `CompositionLocal`s is definitely not suitable here. `remember`ing the