I need to draw the exact same icon several times -...
# compose
s
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
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)
    }
}
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?
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
hmm there is a modifier that I like that is called drawWithCache :
Copy code
Box(modifier = Modifier.drawWithCache {
    val path = Path()//calculate path
    onDrawWithContent { 
        drawPath(path)
    }
})
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
@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
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
Using `CompositionLocal`s is definitely not suitable here. `remember`ing the
Path
is enough.