Skip to content

Instantly share code, notes, and snippets.

@FannyDemey
Last active October 13, 2022 18:49
Show Gist options
  • Save FannyDemey/36bf4aead9cb05ba827e0e19845e2936 to your computer and use it in GitHub Desktop.
Save FannyDemey/36bf4aead9cb05ba827e0e19845e2936 to your computer and use it in GitHub Desktop.
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.height
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.drawWithContent
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.techethic.compose.livrecompose.ui.theme.LivreComposeTheme
@Composable
fun AutoSizeText(
text: String,
textStyle: TextStyle,
modifier: Modifier = Modifier
) {
var scaledTextStyle by remember { mutableStateOf(textStyle) }
var readyToDraw by remember { mutableStateOf(false) }
Text(
text = text,
modifier = modifier.drawWithContent {
if (readyToDraw) {
drawContent()
}
},
style = scaledTextStyle,
onTextLayout = { textLayoutResult ->
if (textLayoutResult.didOverflowHeight) {
scaledTextStyle =
scaledTextStyle.copy(fontSize = scaledTextStyle.fontSize * 0.9 )
} else {
readyToDraw = true
}
}
)
}
@Composable
private fun ScalableTopNavigationContentSample(text: String) {
Row(Modifier.height(56.dp)) {
AutoSizeText(
text = text,
textStyle = MaterialTheme.typography.body2.copy(fontSize = 18.sp)
)
}
}
// Preview fonctionne pas mais ça marche sur device ou en mode interactif
@Preview(fontScale = 1.3f)
@Composable
fun PreviewScalableTopNavigationContent13(){
LivreComposeTheme {
ScalableTopNavigationContentSample(text = "Texte un petit peu long mais voilà c'est pour tester")
}
}
@Preview(fontScale = 1.2f)
@Composable
fun PreviewScalableTopNavigationContent12(){
LivreComposeTheme {
ScalableTopNavigationContentSample(text = "Texte un petit peu long mais voilà c'est pour tester")
}
}
@Preview(fontScale = 1.1f)
@Composable
fun PreviewScalableTopNavigationContent11(){
LivreComposeTheme {
ScalableTopNavigationContentSample(text = "Texte un petit peu long mais voilà c'est pour tester")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment