Home > Mobile >  Pass data from modifier to painter
Pass data from modifier to painter

Time:02-18

How to get data from modifier to pass it to painter. I want to build an address for an image after getting the width of the view in pixels. How can I do it?

Image(
       contentDescription = null,
       modifier = Modifier
                .fillMaxSize()
                .onGloballyPositioned { layoutCoordinates ->
                      layoutCoordinates.size.width                  <--- get width in px
                 },

       painter = rememberImagePainter(
                    data = "https://example.com/width_in_px/image.jpg", <--- pass width in px
                    builder = {
                        size(OriginalSize)
                    },
                )
            )

CodePudding user response:

In Compose you can pass any data using state variables. In my example I'm using a Box to measure size, so you can add image to the view tree only when you know the width. Also I'm using value setter mutable state syntax to allow smart cast.

val (width, setWidth) = remember { mutableStateOf<Int?>(null) }
Box(
    Modifier
        .fillMaxSize()
        .onSizeChanged { size ->
            setWidth(size.width)
        }
) {
    if (width != null) {
        Image(
            contentDescription = null,
            painter = rememberImagePainter(
                data = "https://example.com/${width}/image.jpg",
                builder = {
                    size(OriginalSize)
                },
            ),
            modifier = Modifier
                .matchParentSize()
        )
    }
}
  • Related