Search code examples
kotlinandroid-jetpack-compose

Set the entire component to GrayScale compose


I'm trying to implement a disabled state for a custom component in compose. The disabled state involves having the entire component set to grayscale with an alpha of 0.8f. I tried drawing a rect on top of the component content with BlendMode.Saturation like so;

Surface(
 modifier = modifier.then(Modifier.drawWithCache {
  onDrawWithContent {
   drawContent()
   drawRect(backgroundColor, blendMode = BlendMode.Saturation)
  }
 }.graphicsLayer { alpha = 0.8f }

While this works perfectly fine, the only issue is BlendMode.Saturation is supported API 29 and above. How can I achieve the same behavior on API<29?

Attaching the component screenshot as reference.Screenshot for component


Solution

  • You can draw a ColorMatrix grayscale over entire rect

    context(DrawScope)
    fun drawGrayScale() {
        val colorMatrix = androidx.compose.ui.graphics.ColorMatrix().apply {
            setToSaturation(0f)
        }
        drawRect(color = Color.White, colorFilter = ColorFilter.colorMatrix(colorMatrix))
    }