I'm a little confused and need help with the `aspe...
# compose
k
I'm a little confused and need help with the
aspectRatio
modifier. I am trying to make a composable that has text, and then a square composable that is the height of the text plus a padding of 20. I'm trying to use
aspectRatio
but it always fills the width first so it makes it too big, even if i use
matchHeightConstraintsFirst
Right now I have
Copy code
Box(
   Modifier.height(IntrinsicSize.Min),
   contentAlignment = Alignment.Center,
) {
   Box(
      modifier = Modifier
         .background(Color.Green)
         .fillMaxHeight()
         .aspectRatio(1f),
      )
   Text(
      text = "My Text",
      modifier = Modifier
         .background(Color.Red)
         .padding(20.dp),
   )
}
Currently it looks like the first image but I want it to look like the second
a
It's because you are using
fillMaxHeight()
. it will stretch the parent until it fills the full height (if the parent allows it). Try
matchparentSize()
instead. i think it will work combined with
aspecRatio()
gratitude thank you 2
k
Ah yes that's it, thank you! Here's the final solution
Copy code
Box(contentAlignment = Alignment.Center) {
        Box(
            modifier = Modifier
                .background(Color.Green)
                .matchParentSize()
                .aspectRatio(1f, true),
        )
        Text(
            text = "My Text",
            modifier = Modifier
                .padding(20.dp)
                .background(Color.Red),
        )
    }
👌 1
a
nice one. TIL aspectRatio takes a second param