Skip to content

Instantly share code, notes, and snippets.

@stevdza-san
Last active June 28, 2021 06:58
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 stevdza-san/0582e5569ed2afa04340bf52bd3ebd3a to your computer and use it in GitHub Desktop.
Save stevdza-san/0582e5569ed2afa04340bf52bd3ebd3a to your computer and use it in GitHub Desktop.
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