Alexandre Favre
Alexandre Favre

Reputation: 21

Jetpack Compose - Row of images with a max height

I would like to implement a row of images with a maximum height of 15dp. If the screen is too thin to display the images with a height of 15dp, they should all be resized for the row to fit the screen width (images must always have the same height). I know it looks simple but I can't find a way to make it work.

Here is a quick graphic I made to explain what I want to achieve: enter image description here

Any help would be greatly appreciated.

Upvotes: 0

Views: 4182

Answers (1)

FishHawk
FishHawk

Reputation: 484

The problem here is that you are missing the ratio of width to height. I assume the ratio is 10.

Row(
    modifier = Modifier
        .heightIn(max = 15.dp)
        .aspectRatio(10f)
) {
    listOf(
        1f to Color.Yellow,
        0.7f to Color.Red,
        1.5f to Color.Green,
        1f to Color.Black,
    ).forEach { (w, c) ->
        Box(
            modifier= Modifier
                .fillMaxHeight()
                .weight(w)
                .background(c)
        ) 
    }
}

enter image description here

If you set maxHeight to 1000dp to simulate a smaller screen, the width of Row will be limited to ScreenWidth.

enter image description here


I get it, you want to automatically determine the ratio based on the image size. In compose, the constraint is passed from the outside in, so it would be slightly unnatural to implement such a feature.

Box(
    modifier = Modifier.fillMaxSize(),
    contentAlignment = Alignment.Center
) {
    Column(verticalArrangement = Arrangement.spacedBy(16.dp)) {
        Test(3)
        Test(5)
        Test(15)
    }
}
@Composable
fun Test(times: Int) {
    Row(
        modifier = Modifier
            .heightIn(max = 50.dp)
            .height(IntrinsicSize.Min)
            .background(Color.Yellow),
        horizontalArrangement = Arrangement.spacedBy(4.dp)
    ) {
        repeat(times) {
            val painter = painterResource(id = R.drawable.ic_launcher_background)
            Image(
                painter = painter,
                contentDescription = null,
                modifier = Modifier
                    .fillMaxHeight()
                    .weight(
                        weight = painter.intrinsicSize.width / painter.intrinsicSize.height,
                        fill = false
                    )
            )
        }
    }
}

enter image description here

Upvotes: 1

Related Questions