I can't seem to get the text to the middle of the ...
# compose
j
I can't seem to get the text to the middle of the circle shape. Code in thread 🧵
Copy code
Box(contentAlignment = Alignment.Center,
    modifier = Modifier
        .background(colorResource(id = R.color.green_700), shape = CircleShape)
        .layout { measurable, constraints ->
            // Measure the composable
            val placeable = measurable.measure(constraints)

            //get the current max dimension to assign width=height
            val currentHeight = placeable.height
            var heightCircle = currentHeight
            if (placeable.width > heightCircle)
                heightCircle = placeable.width

            //assign the dimension and the center position
            layout(heightCircle, heightCircle) {
                // Where the composable gets placed
                placeable.placeRelative(
                    0,
                    (heightCircle - currentHeight) / 2
                )
            }
        }) {

    Text(
        modifier = Modifier
            .padding(1.dp)
            .align(Alignment.Center)
            .defaultMinSize(4.dp),
        text = chatUser.user.unRead.toString(),
        textAlign = TextAlign.Center,
        style = MaterialTheme.typography.caption,
        color = Color.White,
    )
}
a
You are placing the text with an x of 0 so it'll always be at the start.
j
How do I place the text in the middle
a
Copy code
placeable.place(
    (heightCircle - placeable.width) / 2,
    (heightCircle - currentHeight) / 2
)
PS. it's a good habit to use variable names that describe their usage exactly.
j
Thanks it's working
t
BTW, you can do this without a custom layout (you might want to tweak
size
and
fontSize
):
Copy code
val size = 24.dp
val fontSize = 12.sp

Box(
    modifier = Modifier
        .background(colorResource(id = R.color.green_700), CircleShape)
        .size(size),
    contentAlignment = Alignment.Center
) {
    Text(
        modifier = Modifier.padding(end = 1.dp), // otherwise slightly off-center
        text = chatUser.user.unRead.toString(),
        fontSize = fontSize,
        style = MaterialTheme.typography.caption,
        color = Color.White,
    )
}
☝️ 2
☝🏻 1
a
I don't think hardcoding text size is a good idea as it can easily break your UI in some specific configurations (different text scales, different fonts, etc). There's no point doing so as layouts are quite lightweight in Compose UI.
c
@Jeff is there a reason you are using a custom layout versus using
contentAlignment
in your
Box
?