https://kotlinlang.org logo
#compose
Title
# compose
s

spierce7

05/06/2022, 4:44 PM
If I have an
Image
, without knowing it’s size, how could I center something on top of the image? I want the the
Image
size to dictate the size of the parent
Box
. How could I do this in compose?
o

Oleksandr Balan

05/06/2022, 4:57 PM
You could use
.align(Alignment.Center)
to center something in the box.
Copy code
Box {
    Image(
        painter = painterResource(R.drawable.jigglypuff),
        contentDescription = null,
        modifier = Modifier
            .border(2.dp, Color.LightGray)
    )
    Text(
        text = "Jigglypuff",
        modifier = Modifier
            .background(Color.LightGray)
            .align(Alignment.Center)
    )
}
Or alternatively you may set
contentAlignment
on the Box component.
Copy code
Box(
    contentAlignment = Alignment.Center
) {
    Image(
        painter = painterResource(R.drawable.jigglypuff),
        contentDescription = null,
        modifier = Modifier
            .border(2.dp, Color.LightGray)
    )
    Text(
        text = "Jigglypuff",
        modifier = Modifier
            .background(Color.LightGray)
    )
}
Does it work for you?
s

spierce7

05/06/2022, 8:49 PM
I was doing something similar. This is the result I was expecting, but I wasn’t getting it.
I must be doing something else wrong!
o

Oleksandr Balan

05/06/2022, 9:32 PM
Could you maybe post a sample?
2 Views