Skip to content

Instantly share code, notes, and snippets.

@fvilarino
Last active March 10, 2023 21:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fvilarino/f7ebfdc64af81d0420e0cbc7b85ed5b6 to your computer and use it in GitHub Desktop.
Save fvilarino/f7ebfdc64af81d0420e0cbc7b85ed5b6 to your computer and use it in GitHub Desktop.
Ticker - Centered Text
@Composable
fun CenteredText(
letter: Char,
modifier: Modifier = Modifier,
textColor: Color = Color.White,
backgroundColor: Color = Color.Black,
fontSize: TextUnit = 96.sp,
) {
// 1
var ascent by remember {
mutableStateOf(0f)
}
var middle by remember {
mutableStateOf(0f)
}
var baseline by remember {
mutableStateOf(0f)
}
var top by remember {
mutableStateOf(0f)
}
var bottom by remember {
mutableStateOf(0f)
}
// 2
val delta: Float by remember {
derivedStateOf {
((bottom - baseline) - (ascent - top)) / 2f
}
}
Text(
text = letter.toString(),
color = textColor,
fontFamily = FontFamily.Monospace,
fontSize = fontSize,
modifier = modifier
.background(backgroundColor)
.drawBehind {
drawLine(
textColor,
Offset(x = 0f, y = center.y),
Offset(x = size.width, y = center.y),
strokeWidth = 2f * density,
)
}
// 3
.offset {
IntOffset(x = 0, y = delta.roundToInt())
},
onTextLayout = { textLayoutResult ->
val layoutInput = textLayoutResult.layoutInput
val fontSizePx = with(layoutInput.density) { layoutInput.style.fontSize.toPx() }
baseline = textLayoutResult.firstBaseline
top = textLayoutResult.getLineTop(0)
bottom = textLayoutResult.getLineBottom(0)
middle = bottom - top
ascent = bottom - fontSizePx
}
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment