# DrawAnnotation

> Attaches custom draw-phase rendering behind or over a text 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") }
        }
    )
}
```
