0

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?

Ralf Wickum
  • 2,850
  • 9
  • 55
  • 103

1 Answers1

1

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()
            )
        )
    )
}
Muthukrishnan Rajendran
  • 11,122
  • 3
  • 31
  • 41