https://kotlinlang.org logo
#compose
Title
# compose
t

Travis Griggs

10/16/2023, 4:18 PM
I have a number of SVG derived Drawables. Drawing them using Icon @Composables is easy and straightforward and nice using painterResource(id). But drawing them in a given box inside of a Canvas.DrawScope, is a little more roundabout. I'm using this recipe:
Copy code
@Composable
fun MyDrawingThing(modifier:Modifier) {
  val id = R.drawable.my_resource
  val context = LocalContext.current
  val drawable = context.resources.getDrawable(resource, null)
  Canvas(modifier) {
    ...
    drawIntoCanvas { canvas ->
      drawable.setTint(myTintColor.toArgb())
      drawable.setBounds(...)
      drawable.draw(canvas.nativeCanvas)
    }
  }
}
Is there a more straightforward recipe/idiom for doing this?
r

romainguy

10/16/2023, 4:23 PM
I don’t see anything roundabout here, that’s the way drawables would be handled with View as well.
You could however create a small layer to make reuse easier in multiple spots, like Accompanist’s `DrawablePainter`: https://google.github.io/accompanist/drawablepainter/
a

Albert Chang

10/17/2023, 1:24 AM
You can also use this:
Copy code
val painter = painterResource(R.drawable.my_resource)
Canvas(modifier) {
    with(painter) {
        draw(size = size, colorFilter = ColorFilter.tint(myTintColor))
    }
}
👍 1
t

Travis Griggs

10/19/2023, 9:01 PM
Thanks @Albert Chang, liked this approach, after I figured out how to fetch the intrinsicSize from the painter (and extend Size.aspectRatio) as well as use translate to put the drawable somewhere other than 0,0
2 Views