Home > Net >  Image scale using aspect ratio coil using jetpack compose
Image scale using aspect ratio coil using jetpack compose

Time:12-06

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)
)

CodePudding user response:

One possible solution to maintain the aspect ratio of the image while displaying it would be to use the CoilImage component provided by the coil-kt library. You can specify the desired width and height of the image, and the CoilImage component will automatically maintain the aspect ratio of the image while displaying it. Here is an example:

val imageUri = "https://example.com/image.jpg"

CoilImage(
  data = imageUri,
  width = 1300,
  height = 1600,
  contentScale = ContentScale.Fit,
  contentDescription = null,
  modifier = Modifier
    .padding(16.dp, 0.dp, 16.dp, 0.dp)
    .fillMaxWidth()
)

You can also use the aspectRatio modifier to explicitly set the aspect ratio of the image, as shown below:

val imageUri = "https://example.com/image.jpg"

CoilImage(
  data = imageUri,
  width = 1300,
  height = 1600,
  contentScale = ContentScale.Fit,
  contentDescription = null,
  modifier = Modifier
    .padding(16.dp, 0.dp, 16.dp, 0.dp)
    .fillMaxWidth()
    .aspectRatio(1600f / 1300f)
)

I hope this helps!

CodePudding user response:

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
        )
)
  • Related