Skip to content

Instantly share code, notes, and snippets.

@stevdza-san
Last active June 28, 2021 06:58
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Embed
What would you like to do?
Superscript/Subscript Text - Jetpack Compose
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.BaselineShift
import androidx.compose.ui.text.withStyle
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.TextUnit
@Composable
fun SuperScriptText(
normalText: String,
normalTextFontSize: TextUnit = MaterialTheme.typography.subtitle1.fontSize,
superText: String,
superTextFontSize: TextUnit = MaterialTheme.typography.overline.fontSize,
superTextFontWeight: FontWeight = FontWeight.Normal
) {
Text(text = buildAnnotatedString {
withStyle(
style = SpanStyle(
fontSize = normalTextFontSize
)
) {
append(normalText)
}
withStyle(
style = SpanStyle(
fontSize = superTextFontSize,
fontWeight = superTextFontWeight,
baselineShift = BaselineShift.Superscript
)
) {
append(superText)
}
})
}
@Composable
@Preview
fun SuperScriptTextPreview() {
Column(
modifier = Modifier
.fillMaxSize()
.background(Color.White)
) {
SuperScriptText(normalText = "Hello", superText = "World!")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment