DrawAnnotation

Known direct subclasses
BackgroundAnnotation

Draws a filled background and optional Border behind an annotated text range.


Attaches custom draw-phase rendering behind or over a text range.

Runs during the Compose draw phase with access to DrawAnnotationScope.textLayoutResult and the resolved [start, end) offsets (DrawAnnotationScope.start and DrawAnnotationScope.end) so callbacks can query per-line bounding boxes via TextLayoutResult.getBoundingBoxesForRange or contour paths via TextLayoutResult.fillPathForRange. Unlike SpanStyle.background, updating or animating state read inside drawBehind or drawOver only invalidates drawing without triggering text measurement or relayout.

Subclassing and State Guidelines

  • Prefer data class or data object subclasses: Reusable decorations should subclass DrawAnnotation as a top-level data class or data object holding only primitive or immutable graphics parameters so structural equals and hashCode are generated automatically. On Android, annotating a data class subclass with @Parcelize and implementing Parcelable allows AnnotatedString.Saver (for example, when saving an AnnotatedString via rememberSaveable(stateSaver = AnnotatedString.Saver)) to persist and restore the annotation across configuration changes and process death. Note that system clipboard copy/paste converts text through platform Spanned representations and does not transport DrawAnnotation instances.

  • Instance reuse and caching: DrawAnnotation implementations may be shared across multiple ranges, shared across multiple Text layouts, or split across sub-ranges when AnnotatedString.subSequence slices text. Hold a reusable Path instance in a private field and pass it as target to TextLayoutResult.fillPathForRange to avoid allocating a Path on each draw pass; TextLayoutResult caches the per-range bounding boxes internally.

  • Avoid capturing heavy references: AnnotatedString instances are frequently cached in ViewModels or long-lived state holders. Avoid non-static inner class subclasses or properties that retain View, Context, or ViewModel references.

  • Visual-only decoration: DrawAnnotation executes imperative canvas commands during the draw phase and is opaque to accessibility services, clipboard copy, and HTML export. Represent semantic meaning alongside DrawAnnotation using SpanStyle, TtsAnnotation, LinkAnnotation, or StringAnnotation.

For standard rounded background fills and borders, use BackgroundAnnotation. For one-off inline decorations, use the DrawAnnotation factory function.

import androidx.compose.foundation.text.BasicText
import androidx.compose.runtime.remember
import androidx.compose.ui.geometry.CornerRadius
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Path
import androidx.compose.ui.text.DrawAnnotation
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.withDrawAnnotation
import androidx.compose.ui.unit.dp

val cachedPath = remember { Path() }
val highlight = remember {
    DrawAnnotation(
        drawBehind = {
            textLayoutResult.fillPathForRange(
                start = start,
                end = end,
                target = cachedPath,
                cornerRadius = CornerRadius(4.dp.toPx()),
            )
            drawPath(cachedPath, color = Color.Yellow.copy(alpha = 0.4f))
        }
    )
}
BasicText(
    buildAnnotatedString {
        append("Compose ")
        withDrawAnnotation(highlight) { append("custom draw annotation") }
    }
)
import androidx.compose.foundation.text.BasicText
import androidx.compose.runtime.remember
import androidx.compose.ui.geometry.CornerRadius
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Path
import androidx.compose.ui.text.DrawAnnotation
import androidx.compose.ui.text.DrawAnnotationScope
import androidx.compose.ui.text.TextLayoutResult
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.withDrawAnnotation
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp

data class HighlightPathDrawAnnotation(val color: Color, val cornerRadius: Dp) :
    DrawAnnotation() {
    // Reuse a single Path instance to avoid allocating a Path on each draw pass.
    // TextLayoutResult caches the underlying range bounding boxes internally, so the same
    // annotation instance can be shared across multiple ranges.
    private val cachedPath = Path()

    override fun DrawAnnotationScope.drawBehind() {
        textLayoutResult.fillPathForRange(
            start = start,
            end = end,
            target = cachedPath,
            cornerRadius = CornerRadius(cornerRadius.toPx()),
        )
        drawPath(cachedPath, color = color)
    }
}

val highlight = remember {
    HighlightPathDrawAnnotation(
        color = Color.Yellow.copy(alpha = 0.4f),
        cornerRadius = 4.dp,
    )
}
BasicText(
    buildAnnotatedString {
        withDrawAnnotation(highlight) { append("First range") }
        append(" and ")
        withDrawAnnotation(highlight) { append("second range") }
    }
)

Summary

Public constructors

Cmn

Public functions

open Unit

Invoked before the text glyphs are painted.

Cmn
open Unit

Invoked after the text glyphs are painted.

Cmn
abstract operator Boolean
equals(other: Any?)

Requires subclasses to implement structural equality.

Cmn
abstract Int

Requires subclasses to implement a structural hash code.

Cmn

Public constructors

DrawAnnotation

DrawAnnotation()

Public functions

DrawAnnotationScope.drawBehind

open fun DrawAnnotationScope.drawBehind(): Unit

Invoked before the text glyphs are painted. The receiver DrawAnnotationScope is aligned with the text layout origin and provides DrawAnnotationScope.textLayoutResult, DrawAnnotationScope.start, and DrawAnnotationScope.end to query geometry for the annotated range.

DrawAnnotationScope.drawOver

open fun DrawAnnotationScope.drawOver(): Unit

Invoked after the text glyphs are painted. The receiver DrawAnnotationScope is aligned with the text layout origin and provides DrawAnnotationScope.textLayoutResult, DrawAnnotationScope.start, and DrawAnnotationScope.end to query geometry for the annotated range.

equals

abstract operator fun equals(other: Any?): Boolean

Requires subclasses to implement structural equality. Using a data class or data object is sufficient.

hashCode

abstract fun hashCode(): Int

Requires subclasses to implement a structural hash code. Using a data class or data object is sufficient.