I have a LazyColumn with remote images. I know the...
# compose
z
I have a LazyColumn with remote images. I know the resolution of the image, I am displaying them using FillWidth, this means the image that might be 300x400 might actually be 600x800 as it's scaled to fill the width. How can I have an empty placeholder that fills the space in the LazyColumn with the same dimension as the resolution that is scaled with FillWidth as well? Right now when the user scrolls the image is 0dp height, but increased in size once the image is loaded. This causes jumps while scrolling. The docs actually mention this as well but I am unsure how to set the correct height https://developer.android.com/jetpack/compose/lists#lazy-layouts-tips
I guess I could use maths, like get the width of the available view content, divide by width of known image width then multiply by the height (or something like that). Surely there's a better way?
j
Modifier.aspectRatio()
z
Copy code
@Composable
private fun AspectRatio() {
  val heightPixels = 1920
  val widthPixels = 1920
  val aspectRatio = (widthPixels.toFloat() / heightPixels.toFloat())

  val heightDp = with(LocalDensity.current) {
    heightPixels.toDp()
  }

  Box(Modifier
    .fillMaxWidth()
    .aspectRatio(aspectRatio)
    .height(heightDp)
    .background(Color.Red)
  ) {
    AsyncImage(
      model = "<https://dummyimage.com/${widthPixels}x${heightPixels}>",
      contentDescription = null,
      contentScale = ContentScale.FillWidth,
      modifier = Modifier.fillMaxWidth().alpha(0.8f)
    )
  }
}
j
You don't need the height, just
Modifier.fillMaxWidth().aspectRatio(w/h)