# DrawAnnotation

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

## API Reference

> Source set: Common

```kotlin
public abstract class DrawAnnotation : Annotation
```

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](https://composables.com/jetpack-compose/androidx.compose.ui/ui-text/functions/DrawAnnotation/api.md) 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](https://composables.com/jetpack-compose/androidx.compose.ui/ui-text/functions/AnnotatedString/api.md) 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](https://composables.com/jetpack-compose/androidx.compose.ui/ui-text/functions/DrawAnnotation/api.md) instances.
- **Instance reuse and caching**: [DrawAnnotation](https://composables.com/jetpack-compose/androidx.compose.ui/ui-text/functions/DrawAnnotation/api.md) 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](https://composables.com/jetpack-compose/androidx.compose.ui/ui-text/classes/TextLayoutResult/api.md) caches the per-range bounding boxes internally.
- **Avoid capturing heavy references**: [AnnotatedString](https://composables.com/jetpack-compose/androidx.compose.ui/ui-text/functions/AnnotatedString/api.md) instances are frequently cached in
`ViewModel`s or long-lived state holders. Avoid non-static `inner class` subclasses or
properties that retain `View`, `Context`, or `ViewModel` references.
- **Visual-only decoration**: [DrawAnnotation](https://composables.com/jetpack-compose/androidx.compose.ui/ui-text/functions/DrawAnnotation/api.md) executes imperative canvas commands during the
draw phase and is opaque to accessibility services, clipboard copy, and HTML export. Represent
semantic meaning alongside [DrawAnnotation](https://composables.com/jetpack-compose/androidx.compose.ui/ui-text/functions/DrawAnnotation/api.md) using [SpanStyle](https://composables.com/jetpack-compose/androidx.compose.ui/ui-text/classes/SpanStyle/api.md), [TtsAnnotation](https://composables.com/jetpack-compose/androidx.compose.ui/ui-text/classes/TtsAnnotation/api.md),
[LinkAnnotation](https://composables.com/jetpack-compose/androidx.compose.ui/ui-text/classes/LinkAnnotation/api.md), or [StringAnnotation](https://composables.com/jetpack-compose/androidx.compose.ui/ui-text/classes/StringAnnotation/api.md).

For standard rounded background fills and borders, use [BackgroundAnnotation](https://composables.com/jetpack-compose/androidx.compose.ui/ui-text/classes/BackgroundAnnotation/api.md). For one-off inline
decorations, use the [DrawAnnotation](https://composables.com/jetpack-compose/androidx.compose.ui/ui-text/functions/DrawAnnotation/api.md) factory function.

## Functions

### drawBehind

> Source set: Common

```kotlin
public open fun DrawAnnotationScope.drawBehind()
```

Invoked before the text glyphs are painted. The receiver [DrawAnnotationScope](https://composables.com/jetpack-compose/androidx.compose.ui/ui-text/interfaces/DrawAnnotationScope/api.md) is aligned
with the text layout origin and provides `DrawAnnotationScope.textLayoutResult`,
`DrawAnnotationScope.start`, and `DrawAnnotationScope.end` to query geometry for the
annotated range.

### drawOver

> Source set: Common

```kotlin
public open fun DrawAnnotationScope.drawOver()
```

Invoked after the text glyphs are painted. The receiver [DrawAnnotationScope](https://composables.com/jetpack-compose/androidx.compose.ui/ui-text/interfaces/DrawAnnotationScope/api.md) is aligned with
the text layout origin and provides `DrawAnnotationScope.textLayoutResult`,
`DrawAnnotationScope.start`, and `DrawAnnotationScope.end` to query geometry for the
annotated range.

## Code Examples

### DrawAnnotationSample

```kotlin
@Sampled
@Composable
fun DrawAnnotationSample() {
    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") }
        }
    )
}
```

### DrawAnnotationSubclassSample

```kotlin
@Sampled
@Composable
fun DrawAnnotationSubclassSample() {
    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") }
        }
    )
}
```
