androidandroid-jetpack-composeandroid-jetpackandroid-graphics

drawImage() with vector drawable, Jetpack Compose Graphics


I was trying to draw a vector drawable (<vector ...> ... </vector>) within the drawScope as mentioned here.
But when I try to use the function given there like
val imageBitmap = ImageBitmap.imageResource(id = R.drawable.my_vector_image)

I get the following error:

java.lang.ClassCastException: android.graphics.drawable.VectorDrawable cannot be cast to android.graphics.drawable.BitmapDrawable

So, does that mean we can't use VectorDrawable with drawImage? Is there a solution for that?


Solution

  • You can draw VectorDrawable inside drawScope via Painter not ImageBitmap.

    @Preview
    @Composable
    private fun DrawSample() {
        val painter: Painter = painterResource(id = R.drawable.vd_dashboard_active)
    
        Canvas(modifier = Modifier.fillMaxSize()){
            with(painter){
                draw(size = Size(200.dp.toPx(), 200.dp.toPx()))
            }
        }
    }
    

    If you wish to change position of drawing you can use translate()

    translate(left = 100f, top = 200f){
        // Your drawing here
    }