androidx.compose.ui.text
In this page, you'll find documentation for types, properties, and functions available in the androidx.compose.ui.text package such as ParagraphStyle, TextStyle, toUpperCase, buildAnnotatedString, and substring.
If you're looking for guidance instead, check out the Text in Compose guide.
Interfaces
AnnotatedString.Annotation |
Defines annotations that specify additional information to apply to ranges of text within the given AnnotatedString. |
Cmn
|
LinkInteractionListener |
An interface triggered when a user interacts with a link in the text |
Cmn
|
Paragraph |
A paragraph of text that is laid out. |
Cmn
android
|
ParagraphIntrinsics |
Calculates and presents the intrinsic width and height of text. |
Cmn
|
TextInclusionStrategy |
The text inclusion strategy used by |
Cmn
|
Classes
AnnotatedString |
The basic data structure of text with multiple styles. |
Cmn
|
AnnotatedString.Builder |
Builder class for AnnotatedString. |
Cmn
|
AnnotatedString.Builder.BulletScope |
Scope for a bullet list |
Cmn
|
AnnotatedString.Range |
The information attached on the text such as a |
Cmn
|
Bullet |
Draws a bullet point next to a paragraph. |
Cmn
|
EmojiSupportMatch |
When to replace emoji with support emoji using androidx.emoji2. |
android
|
LinkAnnotation |
An annotation that represents a clickable part of the text. |
Cmn
|
LinkAnnotation.Clickable |
An annotation that contains a clickable marked with |
Cmn
|
LinkAnnotation.Url |
An annotation that contains a |
Cmn
|
MultiParagraph |
Lays out and renders multiple paragraphs at once. |
Cmn
|
MultiParagraphIntrinsics |
Calculates and provides the intrinsic width and height of text that contains |
Cmn
|
ParagraphStyle |
Paragraph styling configuration for a paragraph. |
Cmn
|
Placeholder |
A placeholder is a rectangle box inserted into text, which tells the text processor to leave an empty space. |
Cmn
|
PlaceholderVerticalAlign |
The settings used to specify how a placeholder is vertically aligned within a text line. |
Cmn
|
PlatformParagraphStyle |
Provides platform specific |
Cmn
android
|
PlatformSpanStyle |
Provides platform specific |
Cmn
android
|
PlatformTextStyle |
Provides platform specific |
Cmn
android
|
SpanStyle |
Styling configuration for a text span. |
Cmn
|
StringAnnotation |
An |
Cmn
|
TextGranularity |
Used by |
Cmn
|
TextLayoutInput |
The data class which holds the set of parameters of the text layout computation. |
Cmn
|
TextLayoutResult |
The data class which holds text layout result. |
Cmn
|
TextLinkStyles |
Represents the styles of the links in the |
Cmn
|
TextMeasurer |
TextMeasurer is responsible for measuring a text in its entirety so that it's ready to be drawn. |
Cmn
|
TextRange |
An immutable text range class, represents a text range from |
Cmn
|
TextStyle |
Styling configuration for a |
Cmn
|
TtsAnnotation |
An annotation that contains the metadata intended for text-to-speech engine. |
Cmn
|
UrlAnnotation |
This class is deprecated. Use LinkAnnotatation.Url(url) instead |
Cmn
|
VerbatimTtsAnnotation |
The text associated with this annotation is a series of characters that have to be read verbatim. |
Cmn
|
Objects
AnnotatedString.Companion |
Cmn
|
|
TextPainter |
Cmn
|
Annotations
ExperimentalTextApi |
Cmn
|
|
InternalTextApi |
Cmn
|
Top-level functions summary
AnnotatedString |
AnnotatedString(text: String, paragraphStyle: ParagraphStyle)Create an AnnotatedString with a |
Cmn
|
AnnotatedString |
AnnotatedString(Create an AnnotatedString with a |
Cmn
|
Paragraph |
Paragraph(Lays out the text in |
Cmn
|
Paragraph |
This function is deprecated. Paragraph that takes maximum allowed width is deprecated, pass constraints instead. |
Cmn
|
Paragraph |
Paragraph(Lays out a given |
Cmn
|
Paragraph |
This function is deprecated. Font.ResourceLoader is deprecated, instead pass FontFamily.Resolver |
Cmn
|
Paragraph |
This function is deprecated. Paragraph that takes maximum allowed width is deprecated, pass constraints instead. |
Cmn
|
ParagraphIntrinsics |
ParagraphIntrinsics(Factory method to create a |
Cmn
|
ParagraphIntrinsics |
This function is deprecated. Use an overload that takes `annotations` instead |
Cmn
|
ParagraphIntrinsics |
This function is deprecated. Font.ResourceLoader is deprecated, instead use FontFamily.Resolver |
Cmn
|
TextRange |
Creates a |
Cmn
|
TextRange |
An immutable text range class, represents a text range from |
Cmn
|
inline AnnotatedString |
buildAnnotatedString(builder: AnnotatedString.Builder.() -> Unit)Build a new AnnotatedString by populating newly created |
Cmn
|
ParagraphStyle |
lerp(start: ParagraphStyle, stop: ParagraphStyle, fraction: Float)Interpolate between two |
Cmn
|
PlatformParagraphStyle |
lerp(Interpolate between two PlatformParagraphStyle's. |
Cmn
android
|
PlatformSpanStyle |
lerp(start: PlatformSpanStyle, stop: PlatformSpanStyle, fraction: Float)Interpolate between two PlatformSpanStyle's. |
Cmn
android
|
SpanStyle |
Interpolate between two span styles. |
Cmn
|
TextStyle |
Interpolate between two text styles. |
Cmn
|
TextMeasurer |
@ComposableCreates and remembers a |
Cmn
|
TextStyle |
resolveDefaults(style: TextStyle, direction: LayoutDirection)Fills missing values in TextStyle with default values and resolve |
Cmn
|
Extension functions summary
AnnotatedString |
AnnotatedString.capitalize(localeList: LocaleList)Create capitalized |
Cmn
|
String |
String.capitalize(localeList: LocaleList)Returns capitalized String. |
Cmn
|
String |
String.capitalize(locale: Locale)Returns capitalized String. |
Cmn
|
TextRange |
Ensures that |
Cmn
|
AnnotatedString |
AnnotatedString.decapitalize(localeList: LocaleList)Create capitalized |
Cmn
|
String |
String.decapitalize(localeList: LocaleList)Returns decapitalized String. |
Cmn
|
String |
String.decapitalize(locale: Locale)Returns decapitalized String. |
Cmn
|
Unit |
DrawScope.drawText(Draw an existing text layout as produced by |
Cmn
|
Unit |
DrawScope.drawText(Draw an existing text layout as produced by |
Cmn
|
Unit |
DrawScope.drawText(Draw text using a TextMeasurer. |
Cmn
|
Unit |
DrawScope.drawText(Draw styled text using a TextMeasurer. |
Cmn
|
AnnotatedString |
AnnotatedString.Companion.fromHtml(Converts a string with HTML tags into |
android
|
String |
CharSequence.substring(range: TextRange) |
Cmn
|
AnnotatedString |
AnnotatedString.toLowerCase(localeList: LocaleList)Create lower case transformed |
Cmn
|
String |
String.toLowerCase(localeList: LocaleList)Returns lowercase transformed String. |
Cmn
|
String |
String.toLowerCase(locale: Locale)Returns lowercase transformed String. |
Cmn
|
AnnotatedString |
AnnotatedString.toUpperCase(localeList: LocaleList)Create upper case transformed |
Cmn
|
String |
String.toUpperCase(localeList: LocaleList)Returns uppercase transformed String. |
Cmn
|
String |
String.toUpperCase(locale: Locale)Returns uppercase transformed String. |
Cmn
|
inline R |
<R : Any> AnnotatedString.Builder.withAnnotation(Pushes an |
Cmn
|
inline R |
@ExperimentalTextApiThis function is deprecated. Use LinkAnnotation API for links instead |
Cmn
|
inline R |
<R : Any> AnnotatedString.Builder.withAnnotation(Pushes an annotation to the |
Cmn
|
inline R |
<R : Any> AnnotatedString.Builder.withLink(Pushes a |
Cmn
|
inline R |
<R : Any> AnnotatedString.Builder.withStyle(Pushes |
Cmn
|
inline R |
<R : Any> AnnotatedString.Builder.withStyle(style: SpanStyle, block: AnnotatedString.Builder.() -> R)Pushes |
Cmn
|
Top-level functions
AnnotatedString
fun AnnotatedString(text: String, paragraphStyle: ParagraphStyle): AnnotatedString
Create an AnnotatedString with a paragraphStyle that will apply to the whole text.
| Parameters | |
|---|---|
text: String |
the text to be styled |
paragraphStyle: ParagraphStyle |
|
AnnotatedString
fun AnnotatedString(
text: String,
spanStyle: SpanStyle,
paragraphStyle: ParagraphStyle? = null
): AnnotatedString
Create an AnnotatedString with a spanStyle that will apply to the whole text.
| Parameters | |
|---|---|
text: String |
the text to be styled |
spanStyle: SpanStyle |
|
paragraphStyle: ParagraphStyle? = null |
|
Paragraph
fun Paragraph(
paragraphIntrinsics: ParagraphIntrinsics,
constraints: Constraints,
maxLines: Int = DefaultMaxLines,
overflow: TextOverflow = TextOverflow.Clip
): Paragraph
Lays out the text in ParagraphIntrinsics with the given constraints. A paragraph is a text that has a single ParagraphStyle.
| Parameters | |
|---|---|
paragraphIntrinsics: ParagraphIntrinsics |
|
constraints: Constraints |
how wide and tall the text is allowed to be. |
maxLines: Int = DefaultMaxLines |
the maximum number of lines that the text can have |
overflow: TextOverflow = TextOverflow.Clip |
specifies how visual overflow should be handled |
Paragraph
funParagraph(
paragraphIntrinsics: ParagraphIntrinsics,
maxLines: Int = DefaultMaxLines,
ellipsis: Boolean = false,
width: Float
): Paragraph
Lays out the text in ParagraphIntrinsics with the given constraints. A paragraph is a text that has a single ParagraphStyle.
| Parameters | |
|---|---|
paragraphIntrinsics: ParagraphIntrinsics |
|
maxLines: Int = DefaultMaxLines |
the maximum number of lines that the text can have |
ellipsis: Boolean = false |
whether to ellipsize text, applied only when |
width: Float |
how wide the text is allowed to be |
Paragraph
fun Paragraph(
text: String,
style: TextStyle,
constraints: Constraints,
density: Density,
fontFamilyResolver: FontFamily.Resolver,
spanStyles: List<AnnotatedString.Range<SpanStyle>> = listOf(),
placeholders: List<AnnotatedString.Range<Placeholder>> = listOf(),
maxLines: Int = DefaultMaxLines,
overflow: TextOverflow = TextOverflow.Clip
): Paragraph
Lays out a given text with the given constraints. A paragraph is a text that has a single ParagraphStyle.
If the style does not contain any androidx.compose.ui.text.style.TextDirection, androidx.compose.ui.text.style.TextDirection.Content is used as the default value.
| Parameters | |
|---|---|
text: String |
the text to be laid out |
style: TextStyle |
the |
constraints: Constraints |
how wide and tall the text is allowed to be. |
density: Density |
density of the device |
fontFamilyResolver: FontFamily.Resolver |
|
spanStyles: List<AnnotatedString.Range<SpanStyle>> = listOf() |
|
placeholders: List<AnnotatedString.Range<Placeholder>> = listOf() |
a list of placeholder metrics which tells |
maxLines: Int = DefaultMaxLines |
the maximum number of lines that the text can have |
overflow: TextOverflow = TextOverflow.Clip |
specifies how visual overflow should be handled |
| Throws | |
|---|---|
kotlin.IllegalArgumentException |
if |
Paragraph
funParagraph(
text: String,
style: TextStyle,
spanStyles: List<AnnotatedString.Range<SpanStyle>> = listOf(),
placeholders: List<AnnotatedString.Range<Placeholder>> = listOf(),
maxLines: Int = DefaultMaxLines,
ellipsis: Boolean = false,
width: Float,
density: Density,
resourceLoader: Font.ResourceLoader
): Paragraph
Lays out a given text with the given constraints. A paragraph is a text that has a single ParagraphStyle.
If the style does not contain any androidx.compose.ui.text.style.TextDirection, androidx.compose.ui.text.style.TextDirection.Content is used as the default value.
| Parameters | |
|---|---|
text: String |
the text to be laid out |
style: TextStyle |
the |
spanStyles: List<AnnotatedString.Range<SpanStyle>> = listOf() |
|
placeholders: List<AnnotatedString.Range<Placeholder>> = listOf() |
a list of placeholder metrics which tells |
maxLines: Int = DefaultMaxLines |
the maximum number of lines that the text can have |
ellipsis: Boolean = false |
whether to ellipsize text, applied only when |
width: Float |
how wide the text is allowed to be |
density: Density |
density of the device |
resourceLoader: Font.ResourceLoader |
|
| Throws | |
|---|---|
kotlin.IllegalArgumentException |
if |
Paragraph
funParagraph(
text: String,
style: TextStyle,
width: Float,
density: Density,
fontFamilyResolver: FontFamily.Resolver,
spanStyles: List<AnnotatedString.Range<SpanStyle>> = listOf(),
placeholders: List<AnnotatedString.Range<Placeholder>> = listOf(),
maxLines: Int = DefaultMaxLines,
ellipsis: Boolean = false
): Paragraph
Lays out a given text with the given constraints. A paragraph is a text that has a single ParagraphStyle.
If the style does not contain any androidx.compose.ui.text.style.TextDirection, androidx.compose.ui.text.style.TextDirection.Content is used as the default value.
| Parameters | |
|---|---|
text: String |
the text to be laid out |
style: TextStyle |
the |
width: Float |
how wide the text is allowed to be |
density: Density |
density of the device |
fontFamilyResolver: FontFamily.Resolver |
|
spanStyles: List<AnnotatedString.Range<SpanStyle>> = listOf() |
|
placeholders: List<AnnotatedString.Range<Placeholder>> = listOf() |
a list of placeholder metrics which tells |
maxLines: Int = DefaultMaxLines |
the maximum number of lines that the text can have |
ellipsis: Boolean = false |
whether to ellipsize text, applied only when |
| Throws | |
|---|---|
kotlin.IllegalArgumentException |
if |
ParagraphIntrinsics
fun ParagraphIntrinsics(
text: String,
style: TextStyle,
annotations: List<AnnotatedString.Range<AnnotatedString.Annotation>>,
density: Density,
fontFamilyResolver: FontFamily.Resolver,
placeholders: List<AnnotatedString.Range<Placeholder>> = listOf()
): ParagraphIntrinsics
Factory method to create a ParagraphIntrinsics.
If the style does not contain any androidx.compose.ui.text.style.TextDirection, androidx.compose.ui.text.style.TextDirection.Content is used as the default value.
| See also | |
|---|---|
ParagraphIntrinsics |
ParagraphIntrinsics
funParagraphIntrinsics(
text: String,
style: TextStyle,
spanStyles: List<AnnotatedString.Range<SpanStyle>> = listOf(),
placeholders: List<AnnotatedString.Range<Placeholder>> = listOf(),
density: Density,
fontFamilyResolver: FontFamily.Resolver
): ParagraphIntrinsics
ParagraphIntrinsics
funParagraphIntrinsics(
text: String,
style: TextStyle,
spanStyles: List<AnnotatedString.Range<SpanStyle>> = listOf(),
placeholders: List<AnnotatedString.Range<Placeholder>> = listOf(),
density: Density,
resourceLoader: Font.ResourceLoader
): ParagraphIntrinsics
Factory method to create a ParagraphIntrinsics.
If the style does not contain any androidx.compose.ui.text.style.TextDirection, androidx.compose.ui.text.style.TextDirection.Content is used as the default value.
| See also | |
|---|---|
ParagraphIntrinsics |
TextRange
fun TextRange(index: Int): TextRange
Creates a TextRange where start is equal to end, and the value of those are index.
TextRange
fun TextRange(start: Int, end: Int): TextRange
An immutable text range class, represents a text range from start (inclusive) to end (exclusive). end can be smaller than start and in those cases min and max can be used in order to fetch the values.
buildAnnotatedString
inline fun buildAnnotatedString(builder: AnnotatedString.Builder.() -> Unit): AnnotatedString
Build a new AnnotatedString by populating newly created AnnotatedString.Builder provided by builder.
import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.AnnotatedString import androidx.compose.ui.text.SpanStyle import androidx.compose.ui.text.buildAnnotatedString import androidx.compose.ui.text.withStyle // create an AnnotatedString using the lambda builder buildAnnotatedString { // append "Hello" with red text color withStyle(SpanStyle(color = Color.Red)) { append("Hello") } append(" ") // append "Hello" with blue text color withStyle(SpanStyle(color = Color.Blue)) { append("World!") } }
| Parameters | |
|---|---|
builder: AnnotatedString.Builder.() -> Unit |
lambda to modify |
lerp
fun lerp(start: ParagraphStyle, stop: ParagraphStyle, fraction: Float): ParagraphStyle
Interpolate between two ParagraphStyles.
This will not work well if the styles don't set the same fields.
The fraction argument represents position on the timeline, with 0.0 meaning that the interpolation has not started, returning start (or something equivalent to start), 1.0 meaning that the interpolation has finished, returning stop (or something equivalent to stop), and values in between meaning that the interpolation is at the relevant point on the timeline between start and stop. The interpolation can be extrapolated beyond 0.0 and 1.0, so negative values and values greater than 1.0 are valid.
lerp
fun lerp(
start: PlatformParagraphStyle,
stop: PlatformParagraphStyle,
fraction: Float
): PlatformParagraphStyle
Interpolate between two PlatformParagraphStyle's.
This will not work well if the styles don't set the same fields.
The fraction argument represents position on the timeline, with 0.0 meaning that the interpolation has not started, returning start (or something equivalent to start), 1.0 meaning that the interpolation has finished, returning stop (or something equivalent to stop), and values in between meaning that the interpolation is at the relevant point on the timeline between start and stop. The interpolation can be extrapolated beyond 0.0 and 1.0, so negative values and values greater than 1.0 are valid.
lerp
fun lerp(start: PlatformSpanStyle, stop: PlatformSpanStyle, fraction: Float): PlatformSpanStyle
Interpolate between two PlatformSpanStyle's.
This will not work well if the styles don't set the same fields.
The fraction argument represents position on the timeline, with 0.0 meaning that the interpolation has not started, returning start (or something equivalent to start), 1.0 meaning that the interpolation has finished, returning stop (or something equivalent to stop), and values in between meaning that the interpolation is at the relevant point on the timeline between start and stop. The interpolation can be extrapolated beyond 0.0 and 1.0, so negative values and values greater than 1.0 are valid.
lerp
fun lerp(start: SpanStyle, stop: SpanStyle, fraction: Float): SpanStyle
Interpolate between two span styles.
This will not work well if the styles don't set the same fields.
The fraction argument represents position on the timeline, with 0.0 meaning that the interpolation has not started, returning start (or something equivalent to start), 1.0 meaning that the interpolation has finished, returning stop (or something equivalent to stop), and values in between meaning that the interpolation is at the relevant point on the timeline between start and stop. The interpolation can be extrapolated beyond 0.0 and 1.0, so negative values and values greater than 1.0 are valid.
lerp
fun lerp(start: TextStyle, stop: TextStyle, fraction: Float): TextStyle
Interpolate between two text styles.
This will not work well if the styles don't set the same fields.
The fraction argument represents position on the timeline, with 0.0 meaning that the interpolation has not started, returning start (or something equivalent to start), 1.0 meaning that the interpolation has finished, returning stop (or something equivalent to stop), and values in between meaning that the interpolation is at the relevant point on the timeline between start and stop. The interpolation can be extrapolated beyond 0.0 and 1.0, so negative values and values greater than 1.0 are valid.
rememberTextMeasurer
@Composable
fun rememberTextMeasurer(cacheSize: Int = DefaultCacheSize): TextMeasurer
Creates and remembers a TextMeasurer. All parameters that are required for TextMeasurer except cacheSize are read from CompositionLocals. Created TextMeasurer carries an internal TextLayoutCache with cacheSize capacity. Provide 0 for cacheSize to opt-out from internal caching behavior.
| Parameters | |
|---|---|
cacheSize: Int = DefaultCacheSize |
Capacity of internal cache inside |
resolveDefaults
fun resolveDefaults(style: TextStyle, direction: LayoutDirection): TextStyle
Fills missing values in TextStyle with default values and resolve TextDirection.
This function will fill all null or TextUnit.Unspecified field with actual values.
| Parameters | |
|---|---|
style: TextStyle |
a text style to be resolved |
direction: LayoutDirection |
a layout direction to be used for resolving text layout direction algorithm |
| Returns | |
|---|---|
TextStyle |
resolved text style. |
Extension functions
capitalize
fun AnnotatedString.capitalize(localeList: LocaleList = LocaleList.current): AnnotatedString
Create capitalized AnnotatedString
The capitalization sometimes maps different number of characters. This function adjusts the text style and paragraph style ranges to transformed offset.
Note, if the style's offset is middle of the capitalization context, this function won't transform the character, e.g. style starts from between base alphabet character and accent character.
| Parameters | |
|---|---|
localeList: LocaleList = LocaleList.current |
A locale list used for capitalize mapping. Only the first locale is effective. If empty locale list is passed, use the current locale instead. Note that, this locale is currently ignored since underlying Kotlin method is experimental. |
| Returns | |
|---|---|
AnnotatedString |
A capitalized string. |
capitalize
fun String.capitalize(localeList: LocaleList): String
Returns capitalized String.
| Parameters | |
|---|---|
localeList: LocaleList |
a locale list object. If empty locale list object is passed, use current locale instead. |
| Returns | |
|---|---|
String |
a transformed text |
capitalize
fun String.capitalize(locale: Locale): String
Returns capitalized String.
| Parameters | |
|---|---|
locale: Locale |
a locale object |
| Returns | |
|---|---|
String |
a transformed text |
coerceIn
fun TextRange.coerceIn(minimumValue: Int, maximumValue: Int): TextRange
Ensures that TextRange.start and TextRange.end values lies in the specified range minimumValue and maximumValue. For each TextRange.start and TextRange.end values:
-
if value is smaller than
minimumValue, value is replaced byminimumValue -
if value is greater than
maximumValue, value is replaced bymaximumValue
| Parameters | |
|---|---|
minimumValue: Int |
the minimum value that |
maximumValue: Int |
the exclusive maximum value that |
decapitalize
fun AnnotatedString.decapitalize(localeList: LocaleList = LocaleList.current): AnnotatedString
Create capitalized AnnotatedString
The decapitalization sometimes maps different number of characters. This function adjusts the text style and paragraph style ranges to transformed offset.
Note, if the style's offset is middle of the decapitalization context, this function won't transform the character, e.g. style starts from between base alphabet character and accent character.
| Parameters | |
|---|---|
localeList: LocaleList = LocaleList.current |
A locale list used for decapitalize mapping. Only the first locale is effective. If empty locale list is passed, use the current locale instead. Note that, this locale is currently ignored since underlying Kotlin method is experimental. |
| Returns | |
|---|---|
AnnotatedString |
A decapitalized string. |
decapitalize
fun String.decapitalize(localeList: LocaleList): String
Returns decapitalized String.
| Parameters | |
|---|---|
localeList: LocaleList |
a locale list object. If empty locale list object is passed, use current locale instead. |
decapitalize
fun String.decapitalize(locale: Locale): String
Returns decapitalized String.
| Parameters | |
|---|---|
locale: Locale |
a locale object |
| Returns | |
|---|---|
String |
a transformed text |
drawText
fun DrawScope.drawText(
textLayoutResult: TextLayoutResult,
brush: Brush,
topLeft: Offset = Offset.Zero,
alpha: Float = Float.NaN,
shadow: Shadow? = null,
textDecoration: TextDecoration? = null,
drawStyle: DrawStyle? = null,
blendMode: BlendMode = DrawScope.DefaultBlendMode
): Unit
Draw an existing text layout as produced by TextMeasurer.
This draw function cannot relayout when async font loading resolves. If using async fonts or other dynamic text layout, you are responsible for invalidating layout on changes.
| Parameters | |
|---|---|
textLayoutResult: TextLayoutResult |
Text Layout to be drawn |
brush: Brush |
The brush to use when drawing the text. |
topLeft: Offset = Offset.Zero |
Offsets the text from top left point of the current coordinate system. |
alpha: Float = Float.NaN |
Opacity to be applied to |
shadow: Shadow? = null |
The shadow effect applied on the text. |
textDecoration: TextDecoration? = null |
The decorations to paint on the text (e.g., an underline). |
drawStyle: DrawStyle? = null |
Whether or not the text is stroked or filled in. |
blendMode: BlendMode = DrawScope.DefaultBlendMode |
Blending algorithm to be applied to the text |
drawText
fun DrawScope.drawText(
textLayoutResult: TextLayoutResult,
color: Color = Color.Unspecified,
topLeft: Offset = Offset.Zero,
alpha: Float = Float.NaN,
shadow: Shadow? = null,
textDecoration: TextDecoration? = null,
drawStyle: DrawStyle? = null,
blendMode: BlendMode = DrawScope.DefaultBlendMode
): Unit
Draw an existing text layout as produced by TextMeasurer.
This draw function cannot relayout when async font loading resolves. If using async fonts or other dynamic text layout, you are responsible for invalidating layout on changes.
import androidx.compose.foundation.Canvas import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.layout.Layout import androidx.compose.ui.layout.layout import androidx.compose.ui.text.TextLayoutResult import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.drawText import androidx.compose.ui.text.rememberTextMeasurer import androidx.compose.ui.unit.sp val textMeasurer = rememberTextMeasurer() var textLayoutResult by remember { mutableStateOf<TextLayoutResult?>(null) } Canvas( Modifier.fillMaxSize().layout { measurable, constraints -> val placeable = measurable.measure(constraints) // TextLayout can be done any time prior to its use in draw, including in a // background thread. // In this sample, text layout is measured in layout modifier. This way the layout // call can be restarted when async font loading completes due to the fact that // `.measure` call is executed in `.layout`. textLayoutResult = textMeasurer.measure(text = "Hello, World!", style = TextStyle(fontSize = 24.sp)) layout(placeable.width, placeable.height) { placeable.placeRelative(0, 0) } } ) { // This happens during draw phase. textLayoutResult?.let { drawText(it) } }
import androidx.compose.animation.animateColor import androidx.compose.animation.core.infiniteRepeatable import androidx.compose.animation.core.rememberInfiniteTransition import androidx.compose.animation.core.tween import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material.LocalTextStyle import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.draw.drawWithCache import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.Layout import androidx.compose.ui.layout.layout import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.drawText import androidx.compose.ui.text.rememberTextMeasurer import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.Constraints // We can disable implicit caching since we will cache in DrawWithCache val textMeasurer = rememberTextMeasurer(cacheSize = 0) // Apply the current text style from theme, otherwise TextStyle.Default will be used. val materialTextStyle = LocalTextStyle.current // Animate color repeatedly val infiniteTransition = rememberInfiniteTransition() val color by infiniteTransition.animateColor( initialValue = Color.Red, targetValue = Color.Blue, animationSpec = infiniteRepeatable(tween(1000)), ) Box( Modifier.fillMaxSize().drawWithCache { // Text layout will be measured just once until the size of the drawing area or // materialTextStyle changes. val textLayoutResult = textMeasurer.measure( text = "Hello, World!", style = materialTextStyle, constraints = Constraints.fixed( width = (size.width / 2).roundToInt(), height = (size.height / 2).roundToInt(), ), overflow = TextOverflow.Ellipsis, ) // color changes will only invalidate draw phase onDrawWithContent { drawContent() drawText( textLayoutResult, color = color, topLeft = Offset( (size.width - textLayoutResult.size.width) / 2, (size.height - textLayoutResult.size.height) / 2, ), ) } } )
| Parameters | |
|---|---|
textLayoutResult: TextLayoutResult |
Text Layout to be drawn |
color: Color = Color.Unspecified |
Text color to use |
topLeft: Offset = Offset.Zero |
Offsets the text from top left point of the current coordinate system. |
alpha: Float = Float.NaN |
opacity to be applied to the |
shadow: Shadow? = null |
The shadow effect applied on the text. |
textDecoration: TextDecoration? = null |
The decorations to paint on the text (e.g., an underline). |
drawStyle: DrawStyle? = null |
Whether or not the text is stroked or filled in. |
blendMode: BlendMode = DrawScope.DefaultBlendMode |
Blending algorithm to be applied to the text |
drawText
fun DrawScope.drawText(
textMeasurer: TextMeasurer,
text: String,
topLeft: Offset = Offset.Zero,
style: TextStyle = TextStyle.Default,
overflow: TextOverflow = TextOverflow.Clip,
softWrap: Boolean = true,
maxLines: Int = Int.MAX_VALUE,
size: Size = Size.Unspecified,
blendMode: BlendMode = DrawScope.DefaultBlendMode
): Unit
Draw text using a TextMeasurer.
This draw function supports only one text style, and async font loading.
TextMeasurer carries an internal cache to optimize text layout measurement for repeated calls in draw phase. If layout affecting attributes like font size, font weight, overflow, softWrap, etc. are changed in consecutive calls to this method, TextMeasurer and its internal cache that holds layout results may not offer any benefits. Check out TextMeasurer and drawText overloads that take TextLayoutResult to learn more about text layout and draw phase optimizations.
import androidx.compose.foundation.Canvas import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.text.drawText import androidx.compose.ui.text.rememberTextMeasurer val textMeasurer = rememberTextMeasurer() Canvas(Modifier.fillMaxSize()) { drawText(textMeasurer, "Hello, World!") }
import androidx.compose.foundation.Canvas import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.drawText import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.rememberTextMeasurer import androidx.compose.ui.text.style.TextDecoration import androidx.compose.ui.unit.sp val textMeasurer = rememberTextMeasurer() Canvas(Modifier.fillMaxSize()) { drawText( textMeasurer = textMeasurer, text = "Hello, World!", style = TextStyle( fontSize = 24.sp, fontWeight = FontWeight.Bold, textDecoration = TextDecoration.Underline, ), ) }
| Parameters | |
|---|---|
textMeasurer: TextMeasurer |
Measures and lays out the text |
text: String |
Text to be drawn |
topLeft: Offset = Offset.Zero |
Offsets the text from top left point of the current coordinate system. |
style: TextStyle = TextStyle.Default |
the |
overflow: TextOverflow = TextOverflow.Clip |
How visual overflow should be handled. |
softWrap: Boolean = true |
Whether the text should break at soft line breaks. If false, the glyphs in the text will be positioned as if there was unlimited horizontal space. If |
maxLines: Int = Int.MAX_VALUE |
An optional maximum number of lines for the text to span, wrapping if necessary. If the text exceeds the given number of lines, it will be truncated according to |
size: Size = Size.Unspecified |
how wide and tall the text should be. If left |
blendMode: BlendMode = DrawScope.DefaultBlendMode |
Blending algorithm to be applied to the text |
drawText
fun DrawScope.drawText(
textMeasurer: TextMeasurer,
text: AnnotatedString,
topLeft: Offset = Offset.Zero,
style: TextStyle = TextStyle.Default,
overflow: TextOverflow = TextOverflow.Clip,
softWrap: Boolean = true,
maxLines: Int = Int.MAX_VALUE,
placeholders: List<AnnotatedString.Range<Placeholder>> = listOf(),
size: Size = Size.Unspecified,
blendMode: BlendMode = DrawScope.DefaultBlendMode
): Unit
Draw styled text using a TextMeasurer.
This draw function supports multi-styling and async font loading.
TextMeasurer carries an internal cache to optimize text layout measurement for repeated calls in draw phase. If layout affecting attributes like font size, font weight, overflow, softWrap, etc. are changed in consecutive calls to this method, TextMeasurer and its internal cache that holds layout results may not offer any benefits. Check out TextMeasurer and drawText overloads that take TextLayoutResult to learn more about text layout and draw phase optimizations.
import androidx.compose.foundation.Canvas import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.text.ParagraphStyle import androidx.compose.ui.text.buildAnnotatedString import androidx.compose.ui.text.drawText import androidx.compose.ui.text.rememberTextMeasurer import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.withStyle val textMeasurer = rememberTextMeasurer() Canvas(Modifier.fillMaxSize()) { drawText( textMeasurer = textMeasurer, text = buildAnnotatedString { withStyle(ParagraphStyle(textAlign = TextAlign.Start)) { append("Hello") } withStyle(ParagraphStyle(textAlign = TextAlign.End)) { append("World") } }, ) }
| Parameters | |
|---|---|
textMeasurer: TextMeasurer |
Measures and lays out the text |
text: AnnotatedString |
Text to be drawn |
topLeft: Offset = Offset.Zero |
Offsets the text from top left point of the current coordinate system. |
style: TextStyle = TextStyle.Default |
the |
overflow: TextOverflow = TextOverflow.Clip |
How visual overflow should be handled. |
softWrap: Boolean = true |
Whether the text should break at soft line breaks. If false, the glyphs in the text will be positioned as if there was unlimited horizontal space. If |
maxLines: Int = Int.MAX_VALUE |
An optional maximum number of lines for the text to span, wrapping if necessary. If the text exceeds the given number of lines, it will be truncated according to |
placeholders: List<AnnotatedString.Range<Placeholder>> = listOf() |
a list of |
size: Size = Size.Unspecified |
how wide and tall the text should be. If left |
blendMode: BlendMode = DrawScope.DefaultBlendMode |
Blending algorithm to be applied to the text |
fromHtml
fun AnnotatedString.Companion.fromHtml(
htmlString: String,
linkStyles: TextLinkStyles? = null,
linkInteractionListener: LinkInteractionListener? = null
): AnnotatedString
Converts a string with HTML tags into AnnotatedString.
If you define your string in the resources, make sure to use HTML-escaped opening brackets < instead of <.
For a list of supported tags go check Styling with HTML markup guide.
To support nested bullet list, the nested sub-list wrapped in
- tag MUST be placed inside a list item with a tag
- . In other words, you must add wrapped sub-list in between opening and closing
- tag of the wrapping sub-list. This is due to the specificities of the underlying XML/HTML parser.
import androidx.compose.foundation.text.BasicText import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.AnnotatedString import androidx.compose.ui.text.fromHtml // First, download a string as a plain text using one of the resources' methods. At this stage // you will be handling plurals and formatted strings in needed. Moreover, the string will be // resolved with respect to the current locale and available translations. val string = stringResource(id = R.string.example) // Next, convert a string marked with HTML tags into AnnotatedString to be displayed by Text val styledAnnotatedString = AnnotatedString.fromHtml(htmlString = string) BasicText(styledAnnotatedString)
Parameters htmlString: StringHTML-tagged string to be parsed to construct AnnotatedString
linkStyles: TextLinkStyles? = nullstyle configuration to be applied to links present in the string in different styles
linkInteractionListener: LinkInteractionListener? = nulla listener that will be attached to links that are present in the string and triggered when user clicks on those links. When set to null, which is a default, the system will try to open the corresponding links with the
androidx.compose.ui.platform.UriHandlercomposition localNote that any link style passed directly to this method will be merged with the styles set directly on a HTML-tagged string. For example, if you set a color of the link via the span annotation to "red" but also pass a green color via the
linkStyles, the link will be displayed as green. If, however, you pass a green background via thelinkStylesinstead, the link will be displayed as red on a green background.Example of displaying styled string from resources
See also LinkAnnotation
toLowerCase
fun AnnotatedString.toLowerCase(localeList: LocaleList = LocaleList.current): AnnotatedString
Create lower case transformed AnnotatedString
The lowercase sometimes maps different number of characters. This function adjusts the text style and paragraph style ranges to transformed offset.
Note, if the style's offset is middle of the lowercase mapping context, this function won't transform the character, e.g. style starts from between base alphabet character and accent character.
| Parameters | |
|---|---|
localeList: LocaleList = LocaleList.current |
A locale list used for lower case mapping. Only the first locale is effective. If empty locale list is passed, use the current locale instead. |
| Returns | |
|---|---|
AnnotatedString |
A lowercase transformed string. |
toLowerCase
fun String.toLowerCase(localeList: LocaleList): String
Returns lowercase transformed String.
| Parameters | |
|---|---|
localeList: LocaleList |
a locale list object. If empty locale list object is passed, use current locale instead. |
| Returns | |
|---|---|
String |
a transformed text |
toLowerCase
fun String.toLowerCase(locale: Locale): String
Returns lowercase transformed String.
| Parameters | |
|---|---|
locale: Locale |
a locale object |
| Returns | |
|---|---|
String |
a transformed text |
toUpperCase
fun AnnotatedString.toUpperCase(localeList: LocaleList = LocaleList.current): AnnotatedString
Create upper case transformed AnnotatedString
The uppercase sometimes maps different number of characters. This function adjusts the text style and paragraph style ranges to transformed offset.
Note, if the style's offset is middle of the uppercase mapping context, this function won't transform the character, e.g. style starts from between base alphabet character and accent character.
| Parameters | |
|---|---|
localeList: LocaleList = LocaleList.current |
A locale list used for upper case mapping. Only the first locale is effective. If empty locale list is passed, use the current locale instead. |
| Returns | |
|---|---|
AnnotatedString |
A uppercase transformed string. |
toUpperCase
fun String.toUpperCase(localeList: LocaleList): String
Returns uppercase transformed String.
| Parameters | |
|---|---|
localeList: LocaleList |
a locale list object. If empty locale list object is passed, use current locale instead. |
| Returns | |
|---|---|
String |
a transformed text |
toUpperCase
fun String.toUpperCase(locale: Locale): String
Returns uppercase transformed String.
| Parameters | |
|---|---|
locale: Locale |
a locale object |
| Returns | |
|---|---|
String |
a transformed text |
withAnnotation
inline fun <R : Any> AnnotatedString.Builder.withAnnotation(
ttsAnnotation: TtsAnnotation,
crossinline block: AnnotatedString.Builder.() -> R
): R
Pushes an TtsAnnotation to the AnnotatedString.Builder, executes block and then pops the annotation.
| Parameters | |
|---|---|
ttsAnnotation: TtsAnnotation |
an object that stores text to speech metadata that intended for the TTS engine. |
crossinline block: AnnotatedString.Builder.() -> R |
function to be executed |
| Returns | |
|---|---|
R |
result of the |
| See also | |
|---|---|
pushStringAnnotation |
|
pop |
withAnnotation
@ExperimentalTextApi
inline fun <R : Any> AnnotatedString.Builder.withAnnotation(
urlAnnotation: UrlAnnotation,
crossinline block: AnnotatedString.Builder.() -> R
): R
Pushes an UrlAnnotation to the AnnotatedString.Builder, executes block and then pops the annotation.
| Parameters | |
|---|---|
urlAnnotation: UrlAnnotation |
A |
crossinline block: AnnotatedString.Builder.() -> R |
function to be executed |
| Returns | |
|---|---|
R |
result of the |
| See also | |
|---|---|
pushStringAnnotation |
|
pop |
withAnnotation
inline fun <R : Any> AnnotatedString.Builder.withAnnotation(
tag: String,
annotation: String,
crossinline block: AnnotatedString.Builder.() -> R
): R
Pushes an annotation to the AnnotatedString.Builder, executes block and then pops the annotation.
| Parameters | |
|---|---|
tag: String |
the tag used to distinguish annotations |
annotation: String |
the string annotation attached on this AnnotatedString |
crossinline block: AnnotatedString.Builder.() -> R |
function to be executed |
| Returns | |
|---|---|
R |
result of the |
| See also | |
|---|---|
pushStringAnnotation |
|
pop |
withLink
inline fun <R : Any> AnnotatedString.Builder.withLink(
link: LinkAnnotation,
block: AnnotatedString.Builder.() -> R
): R
Pushes a LinkAnnotation to the AnnotatedString.Builder, executes block and then pops the annotation.
import androidx.compose.foundation.text.BasicText import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.AnnotatedString import androidx.compose.ui.text.LinkAnnotation import androidx.compose.ui.text.SpanStyle import androidx.compose.ui.text.TextLinkStyles import androidx.compose.ui.text.buildAnnotatedString import androidx.compose.ui.text.withLink import androidx.compose.ui.unit.sp // Display a link in the text BasicText( buildAnnotatedString { append("Build better apps faster with ") withLink( LinkAnnotation.Url( "https://developer.android.com/jetpack/compose", TextLinkStyles(style = SpanStyle(color = Color.Blue)), ) ) { append("Jetpack Compose") } } )
import androidx.compose.foundation.text.BasicText import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.AnnotatedString import androidx.compose.ui.text.LinkAnnotation import androidx.compose.ui.text.SpanStyle import androidx.compose.ui.text.TextLinkStyles import androidx.compose.ui.text.buildAnnotatedString import androidx.compose.ui.text.style.TextDecoration import androidx.compose.ui.text.withLink import androidx.compose.ui.unit.sp // Display a link in the text that gets an underline when hovered BasicText( buildAnnotatedString { append("Build better apps faster with ") val link = LinkAnnotation.Url( "https://developer.android.com/jetpack/compose", TextLinkStyles( style = SpanStyle(color = Color.Blue), hoveredStyle = SpanStyle(textDecoration = TextDecoration.Underline), ), ) withLink(link) { append("Jetpack Compose") } } )
import androidx.compose.foundation.text.BasicText import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalUriHandler import androidx.compose.ui.text.AnnotatedString import androidx.compose.ui.text.LinkAnnotation import androidx.compose.ui.text.SpanStyle import androidx.compose.ui.text.TextLinkStyles import androidx.compose.ui.text.buildAnnotatedString import androidx.compose.ui.text.withLink import androidx.compose.ui.unit.sp // Display a link in the text and log metrics whenever user clicks on it. In that case we handle // the link using openUri method of the LocalUriHandler val uriHandler = LocalUriHandler.current BasicText( buildAnnotatedString { append("Build better apps faster with ") val link = LinkAnnotation.Url( "https://developer.android.com/jetpack/compose", TextLinkStyles(SpanStyle(color = Color.Blue)), ) { val url = (it as LinkAnnotation.Url).url // log some metrics uriHandler.openUri(url) } withLink(link) { append("Jetpack Compose") } } )
| Parameters | |
|---|---|
link: LinkAnnotation |
A |
block: AnnotatedString.Builder.() -> R |
function to be executed |
| Returns | |
|---|---|
R |
result of the |
withStyle
inline fun <R : Any> AnnotatedString.Builder.withStyle(
style: ParagraphStyle,
crossinline block: AnnotatedString.Builder.() -> R
): R
Pushes style to the AnnotatedString.Builder, executes block and then pops the style.
import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.AnnotatedString import androidx.compose.ui.text.SpanStyle import androidx.compose.ui.text.buildAnnotatedString import androidx.compose.ui.text.withStyle buildAnnotatedString { withStyle(SpanStyle(color = Color.Green)) { // green text style will be applied to all text in this block append("Hello") } toAnnotatedString() }
| Parameters | |
|---|---|
style: ParagraphStyle |
|
crossinline block: AnnotatedString.Builder.() -> R |
function to be executed |
| Returns | |
|---|---|
R |
result of the |
withStyle
inline fun <R : Any> AnnotatedString.Builder.withStyle(style: SpanStyle, block: AnnotatedString.Builder.() -> R): R
Pushes style to the AnnotatedString.Builder, executes block and then pops the style.
import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.AnnotatedString import androidx.compose.ui.text.SpanStyle import androidx.compose.ui.text.buildAnnotatedString import androidx.compose.ui.text.withStyle buildAnnotatedString { withStyle(SpanStyle(color = Color.Green)) { // green text style will be applied to all text in this block append("Hello") } toAnnotatedString() }
| Parameters | |
|---|---|
style: SpanStyle |
|
block: AnnotatedString.Builder.() -> R |
function to be executed |
| Returns | |
|---|---|
R |
result of the |