Image scale using aspect ratio coil using jetpack compose

Image scale using aspect ratio coil using jetpack compose

Problem Description:

I need to display image from uri/filepath, big image 1300×1600 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 – 1

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
        )
)
Rate this post
We use cookies in order to give you the best possible experience on our website. By continuing to use this site, you agree to our use of cookies.
Accept
Reject