Skip to content

Instantly share code, notes, and snippets.

@zach-klippenstein
Last active October 6, 2023 07:02
Show Gist options
  • Save zach-klippenstein/ae999af0c4a02cc9911f202bfd835cfd to your computer and use it in GitHub Desktop.
Save zach-klippenstein/ae999af0c4a02cc9911f202bfd835cfd to your computer and use it in GitHub Desktop.
fun Modifier.saturate(saturation: Float): Modifier =
drawWithCache {
// Cache the paint object so it can be reused between draw calls.
val contentPaint = Paint().apply {
colorFilter = ColorFilter.saturate(saturation)
}
onDrawWithContent {
drawIntoCanvas {
it.saveLayer(Rect(Offset.Zero, size), contentPaint)
drawContent()
it.restore()
}
}
}
fun ColorFilter.Companion.saturate(s: Float): ColorFilter {
val saturationMatrix = floatArrayOf(
.213f + .787f * s, .715f - .715f * s, .072f - .072f * s, 0f, 0f,
.213f - .213f * s, .715f + .285f * s, .072f - .072f * s, 0f, 0f,
.213f - .213f * s, .715f - .715f * s, .072f + .928f * s, 0f, 0f,
0f, 0f, 0f, 1f, 0f,
)
return colorMatrix(ColorMatrix(saturationMatrix))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment