Last active
March 10, 2023 21:07
-
-
Save fvilarino/f7ebfdc64af81d0420e0cbc7b85ed5b6 to your computer and use it in GitHub Desktop.
Ticker - Centered Text
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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