Ameer Amjed
01/16/2025, 5:56 AMhorizontalGradient
to animate color changes, and it works fine. However, when I change the layout direction to RTL, it doesn't work correctly. The start
and end
values should change based on the direction, but the animation is not working as expected.Ameer Amjed
01/16/2025, 5:59 AM@Composable
fun AnimatedGradientButton(
modifier: Modifier = Modifier,
onClick: () -> Unit,
initialDelayMillis: Long = 5000,
animationDurationMillis: Int = 5000,
content: @Composable RowScope.() -> Unit
) {
val gradientProgress = remember { Animatable(0f) }
var isGradientAnimating by remember { mutableStateOf(false) }
// Determine the layout direction based on language
val isEnglish = LocalAlmanasaLanguage.current.isEnglish
val layoutDirection = if (isEnglish) LayoutDirection.Ltr else LayoutDirection.Rtl
LaunchedEffect(Unit) {
delay(initialDelayMillis)
isGradientAnimating = true
gradientProgress.animateTo(
targetValue = 1f,
animationSpec = tween(
durationMillis = animationDurationMillis,
easing = LinearEasing
)
)
}
val gradientColors = listOf(
MaximumBlue.copy(alpha = 0.3F),
MaximumBlue.copy(alpha = 0.3F),
MaximumBlue.copy(alpha = 0.3F),
MaximumBlue.copy(alpha = 0.3F),
MaximumBlue,
)
// Adjust the brush direction based on layout direction
val staticBrush = Brush.horizontalGradient(
colors = listOf(MaximumBlue, MaximumBlue)
)
val currentLayoutDirection = LocalLayoutDirection.current
val layoutDirections = if (isEnglish)
LayoutDirection.Ltr
else LayoutDirection.Rtl
val animatedBrush = when (layoutDirection) {
LayoutDirection.Ltr -> Brush.horizontalGradient(
colors = gradientColors,
startX = 0f,
endX = gradientProgress.value * 5000f
)
LayoutDirection.Rtl -> Brush.horizontalGradient(
colors = gradientColors,
startX = gradientProgress.value * 5000f,
endX = 0f
)
}
CompositionLocalProvider(LocalLayoutDirection provides layoutDirections) {
Button(
onClick = onDebounceClick {
onClick()
},
shape = RoundedCornerShape(6.dp),
colors = ButtonDefaults.buttonColors(
containerColor = Color.Transparent,
contentColor = Color.White
),
modifier = modifier
.width(140.dp)
.height(40.dp)
.drawBehind {
drawRoundRect(
brush = if (isGradientAnimating) animatedBrush else staticBrush,
cornerRadius = CornerRadius(6.dp.toPx())
)
},
contentPadding = PaddingValues(9.5.dp)
) {
Text("${layoutDirection}")
// content()
}
}
}
Skaldebane
02/05/2025, 1:19 AMLocalLayoutDirection
, relying on language instead?
That's generally not reliable if you don't override LocalLayoutDirection
higher up in the tree, since the system can request any layout direction regardless of language. If you do override it, then you can just retrieve it directly here instead of checking language (val layoutDirection = LocalLayoutDirection.current
)Skaldebane
02/05/2025, 1:22 AMLocalLayoutDirection
, everything should be mirrored automatically, including drawing operations like the gradient you have here. That's kind of the whole point.