https://kotlinlang.org logo
d

Denis

03/04/2021, 5:21 PM
[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

nglauber

03/04/2021, 6:40 PM
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

Denis

03/04/2021, 7:13 PM
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

Nader Jawad

03/04/2021, 7:27 PM
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

nglauber

03/04/2021, 7:28 PM
Thanks @Nader Jawad 🤝
👍 1
n

Nader Jawad

03/04/2021, 7:31 PM
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

nglauber

03/04/2021, 7:33 PM
I should use
rememberVectorPainter
instead of
VectorPainter
construtor (which is private), right?
n

Nader Jawad

03/04/2021, 7:34 PM
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

Denis

03/04/2021, 7:42 PM
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.
84 Views