androidandroid-jetpack-composecoil

How to measure the size of a Coil AsyncImage with ContentScale.Fit, once loaded?


I have a Coil AsyncImage in Jetpack Compose, as follows:

    AsyncImage(
      model = imageRequest,
      contentDescription = "Ground plan",
      contentScale = ContentScale.Fit,
      modifier = Modifier.fillMaxWidth()
    )

It displays the ground plan of a building and resizes it to the full screen width, while maintaining aspect ratio.

I have a series of buttons that I would like to lay over this ground plan. For each button, I have X and Y coordinates that tell where the button should be located, given the image's original size in pixels.

How do I get the exact size and position of the image inside this AsyncImage Composable (i.e. not of the container), once loaded, so that I can shift and multiply my button coordinates and place the buttons over the image?


Solution

  • I built a library that returns Rect of Bitmap that is drawn inside Image composable, for the purpose of getting Rect of Bitmap that is drawn instead of whole container, however it takes ImageBitmap as parameter but you can easily get ImageBitmap as explained in this answer.

    After getting this rect you can scale rect.start + rectWidth * (positionInBitmp/BitmapWidth) to set X position and same goes for y position as well.

    Let's say you get a Rect(0,200 1000,1200) and you wish to place a button on screen which is on Bitmap at (2000,2000) with width and height of 4000px result will be

    0 + 1000 * 2000/4000 = 500px for x

    200 + 1000 * 2000/4000 = 700px for y

    and you might also need to convert px to dp or use Modifier.offset{} that takes IntOffset.