1

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

2 Answers 2

2

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))
}
2
  • Tried this but calling drawRect() after drawContent() gives me a blank white square. Also just to clarify I need the blendMode.Saturation with a specific gray which is #2D2E2E Mar 10 at 19:29
  • Okay so after a bit of looking around I realized drawRect() on top of drawContent() won't work directly but using the colorMatrix with setToSaturation(0f) would work if this colorMatrix is applied to the paint used in the canvas layer. Thanks @Nikola Despotoski Mar 11 at 19:07
1

Building on top of @Nikola's answer this is what worked for me.

onDrawWithContent {
      val saturationMatrix = ColorMatrix().apply { setToSaturation(0f) }

      val saturationFilter = ColorFilter.colorMatrix(saturationMatrix)
      val paint = Paint().apply {
        colorFilter = saturationFilter
      }
      drawIntoCanvas { canvas ->
        canvas.saveLayer(Rect(0f, 0f, size.width, size.height), paint)
        drawContent()
        canvas.restore()
      }
    }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.