Last active
October 26, 2024 09:03
-
-
Save colinrtwhite/c2966e0b8584b4cdf0a5b05786b20ae1 to your computer and use it in GitHub Desktop.
A painter that wraps another painter to overwrite its color filter, alpha, and/or onDraw.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Create and return a new [Painter] that wraps [painter] with its [alpha], [colorFilter], or [onDraw] overwritten. | |
*/ | |
fun forwardingPainter( | |
painter: Painter, | |
alpha: Float = DefaultAlpha, | |
colorFilter: ColorFilter? = null, | |
onDraw: DrawScope.(ForwardingDrawInfo) -> Unit = DefaultOnDraw, | |
): Painter = ForwardingPainter(painter, alpha, colorFilter, onDraw) | |
data class ForwardingDrawInfo( | |
val painter: Painter, | |
val alpha: Float, | |
val colorFilter: ColorFilter?, | |
) | |
private class ForwardingPainter( | |
private val painter: Painter, | |
private var alpha: Float, | |
private var colorFilter: ColorFilter?, | |
private val onDraw: DrawScope.(ForwardingDrawInfo) -> Unit, | |
) : Painter() { | |
private var info = newInfo() | |
override val intrinsicSize get() = painter.intrinsicSize | |
override fun applyAlpha(alpha: Float): Boolean { | |
if (alpha != DefaultAlpha) { | |
this.alpha = alpha | |
this.info = newInfo() | |
} | |
return true | |
} | |
override fun applyColorFilter(colorFilter: ColorFilter?): Boolean { | |
if (colorFilter != null) { | |
this.colorFilter = colorFilter | |
this.info = newInfo() | |
} | |
return true | |
} | |
override fun DrawScope.onDraw() = onDraw(info) | |
private fun newInfo() = ForwardingDrawInfo(painter, alpha, colorFilter) | |
} | |
private val DefaultOnDraw: DrawScope.(ForwardingDrawInfo) -> Unit = { info -> | |
with(info.painter) { | |
draw(size, info.alpha, info.colorFilter) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
May I ask, why is always setting
null
and theDefaultAlpha
?