Skip to content

Instantly share code, notes, and snippets.

@zach-klippenstein
Last active October 6, 2023 07:02
Show Gist options
  • Select an option

  • Save zach-klippenstein/ae999af0c4a02cc9911f202bfd835cfd to your computer and use it in GitHub Desktop.

Select an option

Save zach-klippenstein/ae999af0c4a02cc9911f202bfd835cfd to your computer and use it in GitHub Desktop.

Revisions

  1. zach-klippenstein revised this gist Mar 22, 2022. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion SaturateModifier.kt
    Original file line number Diff line number Diff line change
    @@ -14,7 +14,7 @@ fun Modifier.saturate(saturation: Float): Modifier =
    }
    }

    private fun ColorFilter.Companion.saturate(s: Float): ColorFilter {
    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,
  2. zach-klippenstein created this gist Mar 22, 2022.
    25 changes: 25 additions & 0 deletions SaturateModifier.kt
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,25 @@
    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()
    }
    }
    }

    private 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))
    }