可以通过以下代码示例实现:
val YellowTheme = MaterialTheme.colors.copy(
primary = Color.Yellow,
secondary = Color.Gray,
)
val IndigoTheme = MaterialTheme.colors.copy(
primary = Color.Indigo,
secondary = Color.Gray,
)
MutableState
变量,用于存储当前选择的主题颜色,例如:val currentColor = remember { mutableStateOf(Color.Yellow) }
LaunchedEffect
实现颜色平滑过渡的效果,例如:LaunchedEffect(currentColor.value) {
val targetColor = if (currentColor.value == YellowTheme.primary) IndigoTheme.primary else YellowTheme.primary
animateColorTransition(targetColor)
}
fun animateColorTransition(targetColor: Color) {
val transition = ColorTransition(currentColor.value, targetColor)
for (color in transition) {
currentColor.value = color
delay(10)
}
}
class ColorTransition(startColor: Color, endColor: Color) : Sequence {
private val fromRed = startColor.red
private val fromGreen = startColor.green
private val fromBlue = startColor.blue
private val toRed = endColor.red
private val toGreen = endColor.green
private val toBlue = endColor.blue
override fun iterator(): Iterator = (0..100).iterator().map { fraction ->
Color(
lerp(fromRed, toRed, fraction / 100f),
lerp(fromGreen, toGreen, fraction / 100f),
lerp(fromBlue, toBlue, fraction / 100f),
)
}
private fun lerp(startValue: Int, endValue: Int, fraction: Float): Int =
(startValue + (fraction * (endValue - startValue))).roundToInt()
}
MaterialTheme
和currentColor
变量为组件设置