Android compose 组件增加流光效果

224 阅读1分钟
fun Modifier.flowLight(
    lightWidth: Dp = Dp(50f),
    durationMillis: Int = 1000,
    delayMillis: Int = 2000,
    colors: List<Color> = listOf(Color.Transparent, Color(0x88FFFFFF), Color.Transparent),
) = composed {
    val transition = rememberInfiniteTransition("light transition")
    val initValue = 0.5f
    val offsetX = transition.animateFloat(
        initialValue = initValue,
        targetValue = 1.5f,
        animationSpec = infiniteRepeatable(
            animation = tween(
                durationMillis = durationMillis,
                easing = FastOutLinearInEasing,
                delayMillis = delayMillis
            ),
            repeatMode = RepeatMode.Restart
        ),
        label = "offsetX"
    )
    val brush = remember(lightWidth) {
        val w = lightWidth.value.dp2px()
        val half = w / 2
        ShaderBrush(
            LinearGradientShader(
                from = Offset(-half, -half),
                to = Offset(half, half),
                colors = colors
            )
        )
    }
    this.drawWithContent {
        drawContent()
        if (offsetX.value <= initValue) {
            translate(size.width * offsetX.value) {
                val w = lightWidth.toPx()
                val half = w / 2f
                drawLine(
                    brush,
                    start = Offset(-size.height - half, size.height + half),
                    end = Offset(0f + half, -half),
                    strokeWidth = w
                )
            }
        }
    }
}