[SOLVED] Is there a way to draw an ImageVector int...
# compose
d
[SOLVED] Is there a way to draw an ImageVector into Canvas? Particularly, I want to draw an Icon. I see
drawImage
method, but it accepts only an ImageBitmap. Probably I need to convert ImageVector to ImageBitmap, but I don't understand how
n
not sure if it’s the best way, but it 👇 worked…
Copy code
val ctx = LocalContext.current
val drawableRes = ContextCompat.getDrawable(ctx, R.drawable.ic_android_orange)

Canvas(...) {
    drawableRes?.let {
        drawImage(
            it.toBitmap(
                width = 96.dp.roundToPx(), 
                height = 96.dp.roundToPx()
            ).asImageBitmap(),
        )
    }
}
d
Wow, thank you, @nglauber! 🙏 That's definitely not something I could've come up with on my own. I'll try it out a bit later.
n
You would need to create a VectorPainter from the ImageVector like so. This approach stays entirely within the compose API surface:
Copy code
val vectorPainter = rememberVectorPainter(myImageVector)
Canvas(modifier = Modifier.size(100.dp)) {
    with(vectorPainter) {
        draw(size)
    }
}
And if you have your own VectorDrawable resource you can do the following:
Copy code
val vectorPainter = painterResource(R.drawable.my_resource)
        Canvas(modifier = Modifier.size(100.dp)) {
            with(vectorPainter) {
                draw(size)
            }
        }
The second example works for all painters (ImagePainters and VectorPainters) the equivalents to BitmapDrawable and VectorDrawable in the framework
n
Thanks @Nader Jawad 🤝
👍 1
n
This solution would be useful for more fine grained drawing logic (i.e. you want to combine several painters to draw in a specific way). The most straight forward approach is to leverage
Modifier.paint(painter)
on any composable
If you look at the implementation of the
Image
composable, internally it uses
Modifier.paint
to do the heavy lifting of all the drawing logic
n
I should use
rememberVectorPainter
instead of
VectorPainter
construtor (which is private), right?
n
Yes that's correct. It should be
rememberVectorPainter
. Apologies we went through a few revisions of this API and it was originally called
VectorPainter
I updated the sample code to reflect this.
😅 1
😉 1
d
Oooh, thank you Nader! ❤️ I saw
rememberVectorPainter
yesterday, but just did not understand how to use it. I tried to call
.draw
on it directly, but ... well I see that now. My lack of Kotlin understanding played against me here.
365 Views