Skip to content Skip to sidebar Skip to footer

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

Solution 1:

As you set flexible width with fillMaxWidth, you need to use ContentScale.FillWidth for your contentScale:

Image(
    painter = rememberImagePainter(
        "https://via.placeholder.com/300.png",
    ),
    contentDescription = null,
    contentScale = ContentScale.FillWidth,
    modifier = Modifier
        .fillMaxWidth()
)

The following will work fine if your image has enough priority. But in some cases coil won't start loading because it's gonna think that image is zero size so no need to display it. For such case you can add size(OriginalSize) parameter to the builder:

rememberImagePainter(
    "https://via.placeholder.com/300.png",
    builder = {
        size(OriginalSize)
    }
)

This parameter makes your view download and put into the memory full size of the image, without optimizing it for the current view. So use it carefully, only if you're sure the image won't be too big and you really can't add use size modifiers.


If image is getting loaded but still not takes enough space, you can set aspect ratio like this:

val painter = rememberImagePainter("https://via.placeholder.com/300.png")
Image(
    painter = painter,
    contentDescription = null,
    contentScale = ContentScale.Fit,
    modifier = Modifier
        .fillMaxWidth()
        .then(
            (painter.state as? ImagePainter.State.Success)
                ?.painter
                ?.intrinsicSize
                ?.let { intrinsicSize ->
                    Modifier.aspectRatio(intrinsicSize.width / intrinsicSize.height)
                } ?: Modifier
        )
)

If none of these helped and painter.state is not changing from Empty, try hardcode height ?: Modifier.height(10.dp) to let image start loading

Post a Comment for "How Do I Create A Jetpack Compose Image That Resizes Automatically Based On A Remotely Loaded Image Size?"