7

I am converting SVG to vector asset by importing it to android studio. How can I draw that vector to canvas with jetpack compose. The only option I see is drawImage, which only takes ImageBitmap. But this is a vector and not a bitmap, so is there a way to just draw ImageVector.

val logoVector: ImageVector = ImageVector.vectorResource(id = R.drawable.diasyst_logo)
V.Rashkov
  • 1,527
  • 4
  • 18
  • 31
  • You can get bitmap from ImageVector. https://stackoverflow.com/questions/33696488/getting-bitmap-from-vector-drawable – mixer Nov 26 '21 at 10:02
  • Is there a more normal way to just draw vector, instead of converting? It just doesn't seem optimal? Also the link above shows examples for Drawable not ImageVector – V.Rashkov Nov 26 '21 at 10:17
  • Is [AndroidView](https://foso.github.io/Jetpack-Compose-Playground/viewinterop/androidview/) suitable for you?If you only want to disaply a VectorDrawable. – mixer Nov 26 '21 at 10:24
  • I would like to draw it on canvas – V.Rashkov Nov 26 '21 at 10:36

2 Answers2

23

You can wrap your ImageVector into a VectorPainter, which is able to render to the standard compose Canvas.

val vector = ImageVector.vectorResource(id = R.drawable.ic_launcher_foreground)
val painter = rememberVectorPainter(image = vector)
Canvas(modifier = Modifier.fillMaxSize()) {
    with(painter) {
        draw(painter.intrinsicSize)
    }
}
Adrian K
  • 3,942
  • 12
  • 15
1

If it is not strictly required to draw in Canvas, the Icon and Image Composables accept a vector graphics resource.

Icon(
 imageVector = ...
 contentDescription = ""
)

Image(
 imageVector = ...
 contentDescription = ""
)

Other than that, the only way is to basically convert the vector to a format you can use inside drawImage method of Canvas. I know you are concerned about performance and optimization, but rest assured, there's no problem using the conversion method