Search code examples
kotlinandroid-jetpack-composecoil

Coil in Jetpack Compose - crop rectangular image with similar width and height


we use Coil to load images. The corresponding AsyncImage should fit into a LazyHorizontalGrid and be croped when the aspect ration does not match the image scale.

This is our code:

AsyncImage(
    model = ImageRequest.Builder(LocalContext.current)
        .data(url)
        .crossfade(true)
        .build(),
    contentDescription = null,
    imageLoader = imageLoader,
    contentScale = ContentScale.Crop,
    modifier = Modifier
        .size(width = size, height = size)
        .padding(4.dp)
        .clip(
            RoundedCornerShape(
                topEnd = 8.dp,
                topStart = 8.dp,
                bottomEnd = 8.dp,
                bottomStart = 8.dp
            )
        )
)

This works well, except that the image keeps its aspect ration but we want it to be rectangular (same width and height) and be cut in case that it is to large.


Solution

  • Not sure if I am understanding the behaviour you want properly... If I have understood correctly, you want the image aspect ratio to fit the rectangle it is loading into regardless of the original image aspect ratio.

    To achieve this I think you can simply change

    ContentScale.Crop
    

    to

    ContentScale.FillBounds
    

    What I don't get is what you mean by "cut in case it is too large".

    if you want the aspect ratio to fit the rectangle, why does it need to be cut? Do you essentially want there to be a zoom?

    In any case, here is a quick guide on what each of the ContentScale options achieve: https://developer.android.com/jetpack/compose/graphics/images/customize#content-scale

    Hope one of them does what you need!