Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create background checker board for image with Jetpack Compose?

I have an image in Compose which may contain transparency. How can I show a checkered background behind the transparent parts of the picture (like in photoshop)?

Example image

like image 911
Mahozad Avatar asked Jan 22 '26 14:01

Mahozad


1 Answers

This is how I've done it:

val watermarkBitmap = ...
Image(
    bitmap = watermarkBitmap,
    contentDescription = null,
    modifier = Modifier
        .size(128.dp)
        .drawBehind {
            // Draws checkerboard in case the image contains transparent parts
            val tileSize = 4f
            val tileCount = (size.width / tileSize).toInt()
            val darkColor = Color.hsl(0f, 0f, 0.8f)
            val lightColor = Color.hsl(1f, 1f, 1f)
            for (i in 0..tileCount) {
                for (j in 0..tileCount) {
                    drawRect(
                        topLeft = Offset(i * tileSize, j * tileSize),
                        color = if ((i + j) % 2 == 0) darkColor else lightColor,
                        size = Size(tileSize, tileSize)
                    )
                }
            }
        }
)

Example result image

like image 117
Mahozad Avatar answered Jan 24 '26 09:01

Mahozad