I am trying to make a square card with items horiz...
# compose
p
I am trying to make a square card with items horizontally aligned in center, thats size is dynamic, base on the content. In my case, the height is always the leading(higher) value. It is not possible to measure twice, so I am trying to use the
IntrinsicSize
and
layout.measure
, but I cannot make it work. I managed to have a square card, but items are not in center. More in thread 👇
this is the card composable:
Copy code
@Composable
fun TestEqualCard() {
    Card(modifier = Modifier.padding(12.dp), backgroundColor = Color.Red) {
        Column(
            modifier = Modifier.then(ChildAspectRatio),
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            Text(text = "1")
            Text(text = "2")
            Text(text = "3")
            Text(text = "4")
            Text(text = "5")
        }
    }
}
ChildAspectRatio that I found on this chat:
Copy code
object ChildAspectRatio : LayoutModifier {
    override fun MeasureScope.measure(
        measurable: Measurable,
        constraints: Constraints
    ): MeasureResult {
        val placeable = measurable.measure(constraints)
        val size = kotlin.math.max(placeable.width, placeable.height)
            .let { constraints.constrain(IntSize(it, it)) }
        return layout(size.width, size.height) {
            placeable.placeRelative(0, 0)
        }
    }
}
result:
Expected result:
I figured it out:
Copy code
private fun Modifier.widthEqualsHeight() = this.then(object : LayoutModifier {
    override fun MeasureScope.measure(
        measurable: Measurable,
        constraints: Constraints
    ): MeasureResult {
        val placeable = measurable.measure(constraints)
        val size = kotlin.math.max(placeable.width, placeable.height)
            .let { constraints.constrain(IntSize(it, it)) }
        return layout(size.width, size.height) {
            placeable.placeRelative(size.width.div(2).minus(placeable.width.div(2)), 0)
        }
    }
})
This modifier cannot be used everywhere, cause it place child horizontally in the center of the parent, but works nicely for this use case.