Skip to content

Instantly share code, notes, and snippets.

@jixiaoyong
Created March 16, 2023 12:16
Show Gist options
  • Save jixiaoyong/1e6175b28f7f284edf1a96e71a53bb37 to your computer and use it in GitHub Desktop.
Save jixiaoyong/1e6175b28f7f284edf1a96e71a53bb37 to your computer and use it in GitHub Desktop.
Jetpack compose写的超长自动滚动的Text
// 文字超长之后,反复向右滑动
BoxWithConstraints {
val parentMaxWidth = constraints.maxWidth
var textWidth by remember { mutableStateOf(parentMaxWidth) }
val anim by rememberInfiniteTransition().animateFloat(
initialValue = 0F,
targetValue = (parentMaxWidth - textWidth).toFloat(),
animationSpec = InfiniteRepeatableSpec(
TweenSpec(
// 根据文字长度调整滚动速度
(textWidth.toFloat() / parentMaxWidth * 2000).toInt(),
easing = LinearEasing
),
)
)
Text(
text = title,
style = titleTextStyle,
maxLines = 1,
overflow = TextOverflow.Visible,
modifier = Modifier
.wrapContentWidth(unbounded = true, align = Alignment.Start)
.offset(
x = anim
.toInt()
.pxToDp()
),
onTextLayout = {
textWidth = it.size.width
}
)
}
@Composable
fun Int.pxToDp() = with(LocalDensity.current) { this@pxToDp.toDp() }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment