How can I center text in a box? My attempt: ```Box...
# compose
m
How can I center text in a box? My attempt:
Copy code
Box(
    modifier = Modifier
        .size(64.dp)  // limit size of aspectRatio. TODO: limit to size of Text (+ padding) somehow
        .aspectRatio(1f)
        .padding(10.dp)
) {
    Row(
        modifier = Modifier
            .padding(2.dp)
            .border(2.dp, color, RoundedCornerShape(6.dp))  // Border around text
            .fillMaxSize(),  // Make sure we're square like the parent
        verticalAlignment = Alignment.CenterVertically,  // place text centered in the square
        horizontalArrangement = Arrangement.Center,
    ) {
        Text(
            metric.source.type.uppercase(),
            style = LocalTextStyle.current.copy(color = color, fontSize = 12.sp, fontWeight = FontWeight.Bold),
        )
    }
}
But the text is aligned closer to the bottom rather than being centered.
s
If your text style has
Copy code
platformStyle = PlatformTextStyle(includeFontPadding = false),
It should center align itself properly. With this code:
Copy code
Box(
  modifier = Modifier
    .size(64.dp)  // limit size of aspectRatio. TODO: limit to size of Text (+ padding) somehow
    .aspectRatio(1f)
    .padding(10.dp),
) {
  Row(
    modifier = Modifier
      .padding(2.dp)
      .border(2.dp, color, RoundedCornerShape(6.dp))  // Border around text
      .fillMaxSize(),  // Make sure we're square like the parent
    verticalAlignment = Alignment.CenterVertically,  // place text centered in the square
    horizontalArrangement = Arrangement.Center,
  ) {
    BasicText(
      "HTTP",
      style = TextStyle(
        color = color,
        fontSize = 12.sp,
        fontWeight = FontWeight.Bold,
        platformStyle = PlatformTextStyle(includeFontPadding = false),
      ),
    )
  }
  HorizontalDivider(Modifier.align(Alignment.Center), color = Color.Black)
}
I get the following screenshot:
This should be set properly in latest compose versions. Could you try with
BasicText
too, to ensure that your custom style is not breaking anything there?
If not, try reading this https://medium.com/androiddevelopers/fixing-font-padding-in-compose-text-768cd232425b perhaps it will give you a good idea of what options you got in your text style