How to change @DrawableRes parameter to Drawable in @Compose function?

1k views Asked by At

Picture function draws picture out of resource id; like R.drawable.icon.

   @Composable
    fun Picture(@DrawableRes resId: Int, modifier: Modifier = Modifier) {
        val rectModifier = loadVectorResource(resId).resource.resource
                ?.let { asset ->
                    modifier.paint(
                            painter = VectorPainter(asset)
                    )
                }
                ?: modifier
        Box(modifier = rectModifier)
    }

How can I change this, so it takes a Drawable argument instead of an @DrawableRes?

1

There are 1 answers

0
Muthukrishnan Rajendran On BEST ANSWER

I am not sure about your scenario, to which you need Drawable instead of the given API.

But we can achieve using the following way. Modifier.paint need just a Painter Object, Painter we can create using both ImagePainter and VectorPainter.

In our case, we want to use Drawable, so we can use ImagePainter and its need ImageAsset, so we can use Bitmap to create ImageAsset.

So the final result will be like:

@Composable
fun Picture(@DrawableRes resId: Int, modifier: Modifier = Modifier) {
    val resources = ResourcesCompat.getDrawable(ContextAmbient.current.resources, resId, null)
    resources?.let {
        Picture(drawable = it, modifier = modifier)
    }
}

@Composable
fun Picture(drawable: Drawable, modifier: Modifier = Modifier) {
    Box(
        modifier = modifier.paint(
            ImagePainter(
                drawable.toBitmap().asImageAsset()
            )
        )
    )
}