Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 104 ยท Jetpack Compose Fundamentals

Text, Images and Icons

Learn to style Text in Compose, use fonts and AnnotatedString spans, load images and vector drawables, add icons, and write good content descriptions.

Text, pictures and small symbols are the content of most screens. In Compose they are three composables: Text, Image and Icon. They look simple, and for a first screen they are, but each has details that separate a polished, accessible app from a rough one: how text is styled and truncated, how a single string can carry several styles, how image files become drawable objects, and what a screen reader says when it meets an icon.

This lesson covers all three. The real code needs the Android SDK and Compose, so the Compose snippets are read-only. The runnable TryIt blocks are plain Kotlin stand-ins: a builder that works like buildAnnotatedString, and a text layout that wraps lines and truncates with an ellipsis the way maxLines and TextOverflow.Ellipsis do. Layout and modifier basics are in Row, Column, Box and Arrangements and Modifiers.

Text and its style

The basic call takes a string and optional styling parameters:

Kotlin
// read-only example: needs Android and Compose
Text(
    text = "Welcome back",
    color = MaterialTheme.colorScheme.primary,
    fontSize = 20.sp,
    fontWeight = FontWeight.SemiBold,
    maxLines = 1,
    overflow = TextOverflow.Ellipsis,
)

Some important details:

  • Sizes use sp, scale-independent pixels, which follow the user's system font-size setting. Use dp for layout sizes and sp for text sizes. Never lock text to a size that ignores the user's accessibility setting.
  • Instead of setting individual properties, prefer a text style from the theme: style = MaterialTheme.typography.titleLarge. A style bundles font size, weight, line height and letter spacing, so your app stays consistent and one theme change updates everything (Material 3 and Theming covers this).
  • maxLines limits the number of lines, and overflow says what happens to the rest. TextOverflow.Ellipsis appends "...", Clip cuts the text off, and Visible lets it spill out.
  • textAlign, lineHeight, letterSpacing, textDecoration (underline, strikethrough) and fontStyle = FontStyle.Italic cover the other common cases.
  • softWrap = false keeps text on one line, and Modifier.basicMarquee() scrolls long single-line text.

For text the user can select and copy, wrap it in SelectionContainer { Text(...) }. For text that comes from a translation file, use stringResource(R.string.welcome) instead of a literal (Accessibility and Localization covers resources and plurals).

Fonts

A font family is built from font files in res/font:

Kotlin
// read-only example: needs Android and Compose
val Inter = FontFamily(
    Font(R.font.inter_regular, FontWeight.Normal),
    Font(R.font.inter_bold, FontWeight.Bold),
)

Text("Hello", fontFamily = Inter, fontWeight = FontWeight.Bold)

Usually you assign the family once in the theme's Typography, so you do not repeat it in every Text. Google Fonts can also be downloaded at runtime through the androidx.compose.ui:ui-text-google-fonts artifact, which keeps the APK smaller at the cost of a first-load delay.

Text that fits: wrapping and ellipsis

Compose measures text inside the constraints it receives. Text wraps at word boundaries when it reaches the maximum width, and if maxLines is set and more lines would be needed, the last visible line is shortened and the overflow rule applies. This is the model the next stand-in implements. It wraps greedily by words, keeps at most maxLines lines, and replaces the end of the last line with "..." when Ellipsis is on. It counts characters, where real text counts pixels, but the mechanism is the same.

Kotlin Wrapping, maxLines and ellipsis (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

In the real system the clipped variant cuts glyphs at the box edge; here it simply shows the first lines. The key lesson is that maxLines limits height and overflow only describes what the visible edge looks like.

AnnotatedString: several styles in one string

Sometimes one paragraph needs bold words, a colored price or a clickable link. Splitting it into several Text composables would break wrapping and screen-reader reading. Instead, use an AnnotatedString: a string plus a list of spans, each a style applied to a character range.

Kotlin
// read-only example: needs Android and Compose
val message = buildAnnotatedString {
    append("Order ")
    withStyle(SpanStyle(fontWeight = FontWeight.Bold)) {
        append("#1042")
    }
    append(" is ")
    withStyle(SpanStyle(color = Color(0xFF2E7D32))) {
        append("shipped")
    }
}
Text(message)

SpanStyle styles characters (weight, color, size, decoration); ParagraphStyle styles whole paragraphs (alignment, indent, line height). For links, LinkAnnotation.Url and LinkAnnotation.Clickable mark a range that responds to taps and is announced as a link. The builder takes a lambda with a receiver (DSL builders explains the pattern), and withStyle records the start position, runs your block, then records a span from that start to the current end.

That is exactly what the stand-in does. It renders the spans as tags so you can see where each style begins and ends, including a nested span.

Kotlin An AnnotatedString span builder (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The span for the italic exclamation mark is nested inside the green span, so the character at the end has both styles. The string is stored once; the ranges are metadata, which is why selection, wrapping and accessibility all keep working.

Images

Image draws a Painter, an object that knows how to draw something. The common painters:

Kotlin
// read-only example: needs Android and Compose
Image(
    painter = painterResource(id = R.drawable.cover),   // PNG, JPG, WebP or vector drawable
    contentDescription = "Book cover for The Rust Handbook",
    modifier = Modifier.size(120.dp).clip(RoundedCornerShape(8.dp)),
    contentScale = ContentScale.Crop,
)
  • painterResource(R.drawable.x) loads a drawable from res/drawable. It works with raster files and with vector drawables, which are XML files that describe shapes with paths. Vector drawables stay sharp at every density and are tiny, so use them for icons and illustrations. Android Studio's Vector Asset tool imports SVG files and Material icons as vector drawables.
  • ImageBitmap and ImageVector can be wrapped with BitmapPainter and rememberVectorPainter.
  • Images from the network are not loaded by Image. A library such as Coil provides AsyncImage for that (Loading Images with Coil).

contentScale decides how the picture fits its box: Crop fills the box and cuts the overflow, Fit shows everything with possible empty space, FillBounds stretches, and Inside only shrinks. Pair Crop with a fixed size and clip for avatars and cards. Remember that drawable resources are chosen by qualifiers (density, night mode, language), covered in The Manifest and Resources.

Icons

Icon draws a monochrome symbol and tints it with the current content color, which is why a Material Button automatically colors its icon to match its label:

Kotlin
// read-only example: needs Android and Compose
Icon(
    imageVector = Icons.Default.Favorite,
    contentDescription = "Add to favorites",
    tint = MaterialTheme.colorScheme.primary,
)

Icons.Default.* come from the material-icons-core set, which contains a small selection. The larger material-icons-extended library has thousands of icons but adds a lot to build time and, without code shrinking, to size, so many teams copy only the vector files they need into res/drawable and use painterResource instead. Use Image when you want an image drawn with its original colors, and Icon when you want a tinted symbol.

contentDescription: what the screen reader says

contentDescription is required by Image and Icon because they have no text of their own. TalkBack reads it aloud. Follow these rules:

  • If the picture carries meaning or triggers an action (a send button, a profile photo that opens a profile), describe the meaning or action, not the artwork: "Send message", not "paper plane icon". Do not add "button" or "image"; the role is announced separately.
  • If it is purely decorative or the text next to it already says the same thing, pass contentDescription = null. Then TalkBack skips it instead of reading noise.
  • Descriptions should come from string resources so that they are translated.

An icon button with a description looks like this: IconButton(onClick = ...) { Icon(Icons.Default.Delete, contentDescription = "Delete note") }. A row with an icon and a text label usually needs null on the icon, because the label already says it.

flowchart LR
    A["Resource<br/>(drawable, vector, font)"] --> B["Painter<br/>(painterResource)"]
    B --> C["Image<br/>original colors"]
    B --> D["Icon<br/>tinted with content color"]

A resource becomes a painter, which Image draws as is and Icon tints.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which unit should you use for text sizes so they follow the user's font-size setting?

    sp (scale-independent pixels) scales with the system font size. dp is for layout dimensions.
  2. 2. What does maxLines = 2 with overflow = TextOverflow.Ellipsis do when the text needs four lines?

    maxLines limits the visible lines. When the text does not fit, the overflow setting decides how the cut-off edge looks; Ellipsis shortens the last line and adds three dots.
  3. 3. Why use an AnnotatedString rather than several Text composables for a sentence with one bold word?

    An AnnotatedString keeps a single string with style ranges (spans), so wrapping, selection and accessibility treat it as one piece of text.
  4. 4. What should contentDescription be for a decorative icon that sits next to a text label saying the same thing?

    Passing null tells accessibility services to skip the element, which avoids reading the same information twice.
  5. 5. What is the main difference between Image and Icon?

    Both draw a painter. Icon applies a tint (the content color by default), which suits monochrome symbols; Image keeps the pixels as they are.

Summary

  • Text sizes use sp; prefer theme text styles over ad hoc properties, and use maxLines plus overflow to control truncation.
  • Fonts come from a FontFamily, usually assigned once in the theme typography.
  • AnnotatedString keeps one string with style spans (SpanStyle, ParagraphStyle, link annotations); build it with buildAnnotatedString and withStyle.
  • Image draws a Painter (painterResource for drawables and vector drawables); contentScale decides how it fits. Network images need a library such as Coil.
  • Icon tints a symbol with the content color; large icon sets cost build time and size.
  • Give meaningful images and icons a contentDescription that describes the purpose, and use null for decorative ones.
  • The Compose code is read-only; the TryIt blocks are stand-ins for text layout and the span builder.

Next: Lazy Lists and Grids