Search code examples
androidkotlinandroid-jetpack-composeaspect-ratiocoil

Image scale using aspect ratio coil using jetpack compose


I need to display image from uri/filepath, big image 1300x1600 resolution. Need to maintain aspect ratio. i tried with coil but didn't give desirable result, still shows big image. not sure whats wrong here what i tried

val painter =
    rememberAsyncImagePainter(imageUri.value)

Image(
    painter = painter,
    contentScale = ContentScale.Fit,
    contentDescription = null,
    modifier = Modifier
        .padding(16.dp, 0.dp, 16.dp, 0.dp)
        .fillMaxWidth()
        .aspectRatio(painter.intrinsicSize.height / painter.intrinsicSize.width)
)


Solution

  • You are getting size unspecified if one of view width/height is calculated as zero.

    You can use something like:

    Image(
        painter = painter,
        contentScale = ContentScale.Fit,
        contentDescription = "contentDescription",
        modifier = Modifier
            .padding(16.dp, 0.dp, 16.dp, 0.dp)
            .fillMaxWidth()
            .then(
                (painter.state as? AsyncImagePainter.State.Success)
                    ?.painter
                    ?.intrinsicSize
                    ?.let { intrinsicSize ->
                        Modifier.aspectRatio(intrinsicSize.width / intrinsicSize.height)
                    } ?: Modifier
            )
    )