Home > Software engineering >  How to overlay texts on an Image using jetpack compose
How to overlay texts on an Image using jetpack compose

Time:11-27

I am trying to make something that uses the same concept as the image below;

enter image description here

An image like background with text overlaying it.

I tried to make a card and give it a backgroundColor of the image, but I got an error;

enter image description here

What I want to do is overlay some texts on an image, like the image above.

So please how do I arrange this code. I need everything to be in a single composable because I need to populate it.

Thanks for your understanding and assistance, In advance.

Please, I'd happily provide any more info needed.

CodePudding user response:

Use a Box to overlay composables.

Something like:

@Composable
fun ImageAndText(
    modifier: Modifier = Modifier,
    painter: Painter,
    contentDescription: String,
    text: String 
) {
    val shape =  RoundedCornerShape(8.dp)
    val height = 100.dp
    Box(
        modifier = modifier
            .height(height)
            .fillMaxWidth()
            .background(White, shape = shape),
        contentAlignment = Alignment.Center
    ) {
        Image(
            painter = painter,
            contentDescription = contentDescription,
            contentScale = ContentScale.Crop,
            modifier = Modifier
                .fillMaxSize()
                .clip(shape)
        )

        Text(
            text = text, 
            color = White
        )

    }
}

enter image description here

CodePudding user response:

You can use Box as a direct Child of your Card and put the Image and Text in it and set its contentAlignment to Alignment.Center.

Use the Image composable to host your desired image instead of card's backgroundColor since it only accepts Color.

@Composable
fun ImageWithTextInMiddle() {
    Card {
        Box(
            modifier = Modifier
                .height(100.dp)
                .fillMaxWidth(),
            contentAlignment = Alignment.Center
        ) {
            Image(
                // painterResource(successInfo.successInfoImageId)
                painterResource(R.drawable.img),
                contentDescription = "",
                contentScale = ContentScale.Crop,
                modifier = Modifier.fillMaxSize()
            )

            // will display in the middle of the image
            Text("Some Text In the middle")
        }
    }
}

enter image description here

  • Related