'How do I create a Jetpack Compose Image that resizes automatically based on a remotely loaded image size?

I would like to display an image with the following rules:

  • The image is remote and needs to load on runtime.
  • We don't know what the image size is until it's loaded.
  • The Image view should take the full width of the parent, and it should automatically adjust its height to match the remotely loaded image, so that no cropping/stretching occurs.

I tried using the Coil dependency and I have this code:

Image(
    painter = rememberImagePainter(viewModel.fullImageUrl),
    contentDescription = null,
    contentScale = ContentScale.FillHeight,
    modifier = Modifier
        .fillMaxWidth()
        .aspectRatio(3.21428f) // TODO: Figure out how to set height/ratio based on image itself
)

When I remove the Image's contentScale and modifier, its height always seems to be zero. I'm not sure what I should do to make Image fill the max width of its parent while determining its own size after Coil loads the image file.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source