Search code examples
androidimageandroid-jetpack-composecompose-multiplatformandroid-compose-image

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


Solution

  • 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