# BackgroundAnnotation

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

## API Reference

> Source set: Common

```kotlin
public class BackgroundAnnotation private constructor(
    public val color: Color = Color.Unspecified,
    public val colorProducer: ColorProducer? = null,
    public val brush: Brush? = null,
    public val cornerRadius: Dp = DefaultCornerRadius,
    public val spread: SpreadValues = DefaultSpread,
    @get:Suppress("GetterSetterNames") public val mergeLines: Boolean = DefaultMergeLines,
    public val border: Border? = null,
    public val alpha: Float = DefaultAlpha,
) : DrawAnnotation()
```

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

Use [BackgroundAnnotation](https://composables.com/jetpack-compose/androidx.compose.ui/ui-text/classes/BackgroundAnnotation/api.md) instead of `SpanStyle.background` to draw rounded multi-line
highlights, inline pills with `Border`s, or draw-phase color and brush animations without
triggering text measurement or relayout.

How multi-line ranges are drawn depends on `mergeLines`:
- `mergeLines = true` (default): Overlapping boxes on adjacent lines merge into a single shape.
Vertical `spread` applies only to the top of the first line and the bottom of the last line,
keeping the inner seams between lines connected.
- `mergeLines = false`: Each line is drawn as a separate rounded rectangle. A negative vertical
`spread` (for example, `SpreadValues(vertical = (-2).dp)`) shrinks each box's top and bottom
edges to leave a gap between lines.

```
mergeLines = true (unified contour):    mergeLines = false (per-line pills):
.----------.                            .----------.
Hello, | world    |                     Hello, | world    |
.------'   .------'                            '----------'
| again    | now.                       .----------.
'----------'                            | again    | now.
'----------'
```

Note: `AnnotatedString.Saver` does not save or restore [BackgroundAnnotation](https://composables.com/jetpack-compose/androidx.compose.ui/ui-text/classes/BackgroundAnnotation/api.md) instances.

## Functions

### drawBehind

> Source set: Common

```kotlin
override fun DrawAnnotationScope.drawBehind()
```

### equals

> Source set: Common

```kotlin
override fun equals(other: Any?): Boolean
```

### hashCode

> Source set: Common

```kotlin
override fun hashCode(): Int
```

### toString

> Source set: Common

```kotlin
override fun toString(): String
```

## Members

### SpreadValues

> Source set: Common

```kotlin
public class SpreadValues(
        public val left: Dp = 0.dp,
        public val top: Dp = 0.dp,
        public val right: Dp = 0.dp,
        public val bottom: Dp = 0.dp,
    )
```

Per-edge `Dp` spread applied to a text range's bounding boxes during the draw phase.

Spread applies to the per-line boxes returned by `TextLayoutResult.getBoundingBoxesForRange`,
rather than to each glyph individually:
- Neighboring characters on the same line whose horizontal bounds touch or overlap are merged
into a single box spanning the line's ``top, bottom``.
- Multi-line ranges and bidirectional text ranges that split into separate visual runs on the
same line produce one box per run.

By default (`SpreadValues.Zero`), each box spans the full line height (``top, bottom``) and
fits tightly around the glyphs horizontally. Configure `BackgroundAnnotation.spread` with
`SpreadValues` to adjust those bounds at draw time without shifting text layout:
- Positive horizontal spread (for example, `SpreadValues(horizontal = 4.dp)`) expands the
left and right edges outward to add space between the first or last glyph and a pill's
border or rounded corners. If horizontal expansion causes two separate boxes on the same
line to touch or overlap, they are merged into a single box.
- Negative vertical spread (for example, `SpreadValues(vertical = (-2).dp)`): when
`BackgroundAnnotation.mergeLines` is `false`, shrinks each per-line box's top and bottom
edges inward from the line bounds so pills on consecutive lines have a vertical gap instead
of touching; when `BackgroundAnnotation.mergeLines` is `true`, shrinks only the outer top
of the first line and outer bottom of the last line of each merged stack while inner line
seams remain joined as a continuous contour.
- Positive vertical spread expands the top and bottom edges outward past the line bounds (on
each per-line box when `mergeLines = false`, or on the outer top and bottom of each merged
stack when `mergeLines = true`).

If negative spread values reduce a box's width or height (or a merged line stack's height) to
`<= 0`, that box or stack is omitted and not drawn.

## Functions

### equals

> Source set: Common

```kotlin
override fun equals(other: Any?): Boolean
```

Creates `SpreadValues` with `all` four edges spread by the same amount.

### hashCode

> Source set: Common

```kotlin
override fun hashCode(): Int
```

## Members

### Companion

> Source set: Common

```kotlin
public companion object
```

## Properties

### Zero

> Source set: Common

```kotlin
public val Zero: SpreadValues = SpreadValues(0.dp, 0.dp, 0.dp, 0.dp)
```

A `SpreadValues` with `0.dp` spread on all four edges.

### Border

> Source set: Common

```kotlin
public class Border private constructor(
        public val width: Dp,
        public val color: Color,
        public val colorProducer: ColorProducer?,
        public val brush: Brush?,
    )
```

Border stroke specification for [BackgroundAnnotation](https://composables.com/jetpack-compose/androidx.compose.ui/ui-text/classes/BackgroundAnnotation/api.md).

Equivalent to `BorderStroke` in `androidx.compose.foundation` (which `ui-text` does not
depend on), with an additional `ColorProducer` overload for draw-phase color animations.

Drawn as a centered stroke along the background contour: half of `width` extends outside the
contour (past `spread`) and half overlaps inside the fill.

## Functions

### equals

> Source set: Common

```kotlin
override fun equals(other: Any?): Boolean
```

Creates a `Border` with a stroke `width` painted with a `brush`.

#### Parameters

| | |
| --- | --- |
| width | stroke width, or `Dp.Hairline` for a single-pixel hairline stroke |
| brush | stroke brush applied to the contour border |

### hashCode

> Source set: Common

```kotlin
override fun hashCode(): Int
```

### toString

> Source set: Common

```kotlin
override fun toString(): String
```

## Code Examples

### BackgroundAnnotationSample

```kotlin
@Sampled
@Composable
fun BackgroundAnnotationSample() {
    val text = remember {
        buildAnnotatedString {
            append("Use ")
            withDrawAnnotation(
                BackgroundAnnotation(
                    color = Color.Cyan.copy(alpha = 0.2f),
                    cornerRadius = 6.dp,
                    spread = SpreadValues(horizontal = 4.dp, vertical = 2.dp),
                    border = BackgroundAnnotation.Border(width = 1.dp, color = Color.Blue),
                )
            ) {
                append("BackgroundAnnotation")
            }
            append(" to draw rounded backgrounds and borders.")
        }
    }
    BasicText(text = text)
}
```

### BackgroundAnnotationSpreadSample

```kotlin
@Sampled
@Composable
fun BackgroundAnnotationSpreadSample() {
    val text = remember {
        buildAnnotatedString {
            append("Use positive horizontal and negative vertical ")
            withDrawAnnotation(
                BackgroundAnnotation(
                    color = Color.Cyan.copy(alpha = 0.25f),
                    cornerRadius = 6.dp,
                    // Positive horizontal spread adds side space around the glyphs;
                    // negative vertical spread shrinks from the line top/bottom so wrapped pills
                    // on consecutive lines stay visually separated instead of touching.
                    spread = SpreadValues(horizontal = 4.dp, vertical = (-2).dp),
                    mergeLines = false,
                    border = BackgroundAnnotation.Border(width = 1.dp, color = Color.Blue),
                )
            ) {
                append("SpreadValues on multi-line per-line pills")
            }
            append(" so adjacent lines do not touch.")
        }
    }
    BasicText(text = text, style = TextStyle(fontSize = 16.sp, lineHeight = 24.sp))
}
```

### BackgroundAnnotationColorProducerSample

```kotlin
@Sampled
@Composable
fun BackgroundAnnotationColorProducerSample() {
    val transition = rememberInfiniteTransition(label = "highlight")
    val animatedColor by
        transition.animateColor(
            initialValue = Color.Cyan.copy(alpha = 0.2f),
            targetValue = Color.Cyan.copy(alpha = 0.6f),
            animationSpec = infiniteRepeatable(tween(1000), RepeatMode.Reverse),
            label = "highlightColor",
        )
    val text = remember {
        buildAnnotatedString {
            append("Animate ")
            withDrawAnnotation(
                BackgroundAnnotation(
                    colorProducer = { animatedColor },
                    cornerRadius = 6.dp,
                    spread = SpreadValues(horizontal = 4.dp, vertical = 2.dp),
                )
            ) {
                append("draw-phase color")
            }
            append(" without recomposing or re-measuring text.")
        }
    }
    BasicText(text = text)
}
```

### BackgroundAnnotationBrushSample

```kotlin
@Sampled
@Composable
fun BackgroundAnnotationBrushSample() {
    val gradientBrush = remember {
        Brush.horizontalGradient(
            colors =
                listOf(
                    Color.Cyan.copy(alpha = 0.3f),
                    Color.Magenta.copy(alpha = 0.3f),
                    Color.Red.copy(alpha = 0.3f),
                )
        )
    }
    val borderGradientBrush = remember {
        Brush.horizontalGradient(colors = listOf(Color.Blue, Color.Magenta))
    }
    val text = remember {
        buildAnnotatedString {
            append("Use a ")
            withDrawAnnotation(
                BackgroundAnnotation(
                    brush = gradientBrush,
                    cornerRadius = 6.dp,
                    spread = SpreadValues(horizontal = 4.dp, vertical = 2.dp),
                    border = BackgroundAnnotation.Border(width = 1.dp, brush = borderGradientBrush),
                )
            ) {
                append("gradient Brush background")
            }
            append(" with a matching gradient border.")
        }
    }
    BasicText(text = text)
}
```
