BackgroundAnnotation


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

Use BackgroundAnnotation instead of SpanStyle.background to draw rounded multi-line highlights, inline pills with Borders, 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 instances.

import androidx.compose.foundation.text.BasicText
import androidx.compose.runtime.remember
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.BackgroundAnnotation
import androidx.compose.ui.text.BackgroundAnnotation.SpreadValues
import androidx.compose.ui.text.DrawAnnotation
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.withDrawAnnotation
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp

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)
import androidx.compose.foundation.text.BasicText
import androidx.compose.runtime.remember
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.BackgroundAnnotation
import androidx.compose.ui.text.BackgroundAnnotation.SpreadValues
import androidx.compose.ui.text.DrawAnnotation
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.withDrawAnnotation
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp

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))
import androidx.compose.animation.animateColor
import androidx.compose.animation.core.RepeatMode
import androidx.compose.animation.core.infiniteRepeatable
import androidx.compose.animation.core.rememberInfiniteTransition
import androidx.compose.animation.core.tween
import androidx.compose.foundation.text.BasicText
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.BackgroundAnnotation
import androidx.compose.ui.text.BackgroundAnnotation.SpreadValues
import androidx.compose.ui.text.DrawAnnotation
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.withDrawAnnotation
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp

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)
import androidx.compose.foundation.text.BasicText
import androidx.compose.runtime.remember
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.BackgroundAnnotation
import androidx.compose.ui.text.BackgroundAnnotation.SpreadValues
import androidx.compose.ui.text.DrawAnnotation
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.withDrawAnnotation
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp

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)

Summary

Nested types

Border stroke specification for BackgroundAnnotation.

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

Public constructors

BackgroundAnnotation(
    brush: Brush,
    cornerRadius: Dp,
    spread: BackgroundAnnotation.SpreadValues,
    mergeLines: Boolean,
    border: BackgroundAnnotation.Border?,
    alpha: @FloatRange(from = 0.0, to = 1.0) Float
)

Creates a BackgroundAnnotation filled with a brush.

Cmn
BackgroundAnnotation(
    color: Color,
    cornerRadius: Dp,
    spread: BackgroundAnnotation.SpreadValues,
    mergeLines: Boolean,
    border: BackgroundAnnotation.Border?,
    alpha: @FloatRange(from = 0.0, to = 1.0) Float
)

Creates a BackgroundAnnotation filled with a static solid color.

Cmn
BackgroundAnnotation(
    colorProducer: ColorProducer,
    cornerRadius: Dp,
    spread: BackgroundAnnotation.SpreadValues,
    mergeLines: Boolean,
    border: BackgroundAnnotation.Border?,
    alpha: @FloatRange(from = 0.0, to = 1.0) Float
)

Creates a BackgroundAnnotation whose fill color is resolved lazily on each draw pass via colorProducer, enabling animations without relayout.

Cmn

Public functions

open Unit

Invoked before the text glyphs are painted.

Cmn
open operator Boolean
equals(other: Any?)

Requires subclasses to implement structural equality.

Cmn
open Int

Requires subclasses to implement a structural hash code.

Cmn
open String
Cmn

Public properties

Float

opacity applied to both fill and border, from 0.0f to 1.0f; defaults to 1.0f

Cmn
BackgroundAnnotation.Border?

optional Border drawn as a centered stroke along the background contour (half of Border.width extends outside the contour and half overlaps inside the fill); defaults to null (no border)

Cmn
Brush?

fill brush drawn behind the annotated range, or null when constructed with color or colorProducer

Cmn
Color

fill color drawn behind the annotated range, or Color.Unspecified when constructed with colorProducer or brush

Cmn
ColorProducer?

deferred color producer evaluated during the draw phase, or null when constructed with color or brush

Cmn
Dp

radius applied to outer and inner corners of the contour; defaults to 0.dp.

Cmn
Boolean

whether vertically adjacent boxes on consecutive lines that overlap horizontally join into a single continuous contour (true) or draw as independent per-line rounded rectangles (false); defaults to true

Cmn
BackgroundAnnotation.SpreadValues

per-edge draw-phase spread applied to the range's bounding boxes (positive values expand outward, negative values shrink inward) without affecting text layout; defaults to SpreadValues.Zero.

Cmn

Inherited functions

From androidx.compose.ui.text.DrawAnnotation
open Unit

Invoked after the text glyphs are painted.

Cmn

Public constructors

BackgroundAnnotation

BackgroundAnnotation(
    brush: Brush,
    cornerRadius: Dp = DefaultCornerRadius,
    spread: BackgroundAnnotation.SpreadValues = DefaultSpread,
    mergeLines: Boolean = DefaultMergeLines,
    border: BackgroundAnnotation.Border? = null,
    alpha: @FloatRange(from = 0.0, to = 1.0) Float = DefaultAlpha
)

Creates a BackgroundAnnotation filled with a brush.

Parameters
brush: Brush

fill brush drawn behind the annotated range

cornerRadius: Dp = DefaultCornerRadius

radius applied to outer and inner corners of the contour; defaults to 0.dp. Coerced to at most half the length of the adjacent edge

spread: BackgroundAnnotation.SpreadValues = DefaultSpread

per-edge draw-phase spread applied to the range's bounding boxes (positive expands outward, negative shrinks inward); defaults to SpreadValues.Zero

mergeLines: Boolean = DefaultMergeLines

whether vertically adjacent overlapping boxes on consecutive lines join into a single contour (true) or draw as independent rounded rectangles (false); defaults to true

border: BackgroundAnnotation.Border? = null

optional Border drawn as a centered stroke along the background contour; defaults to null (no border)

alpha: @FloatRange(from = 0.0, to = 1.0) Float = DefaultAlpha

opacity applied to both fill and border, from 0.0f to 1.0f; defaults to 1.0f

BackgroundAnnotation

BackgroundAnnotation(
    color: Color,
    cornerRadius: Dp = DefaultCornerRadius,
    spread: BackgroundAnnotation.SpreadValues = DefaultSpread,
    mergeLines: Boolean = DefaultMergeLines,
    border: BackgroundAnnotation.Border? = null,
    alpha: @FloatRange(from = 0.0, to = 1.0) Float = DefaultAlpha
)

Creates a BackgroundAnnotation filled with a static solid color.

For animated colors, use the ColorProducer constructor (BackgroundAnnotation(colorProducer = ...)) instead so color changes are resolved during the draw phase without recomposing or re-measuring text.

Parameters
color: Color

static fill color drawn behind the annotated range

cornerRadius: Dp = DefaultCornerRadius

radius applied to outer and inner corners of the contour; defaults to 0.dp. Coerced to at most half the length of the adjacent edge

spread: BackgroundAnnotation.SpreadValues = DefaultSpread

per-edge draw-phase spread applied to the range's bounding boxes (positive expands outward, negative shrinks inward); defaults to SpreadValues.Zero

mergeLines: Boolean = DefaultMergeLines

whether vertically adjacent overlapping boxes on consecutive lines join into a single contour (true) or draw as independent rounded rectangles (false); defaults to true

border: BackgroundAnnotation.Border? = null

optional Border drawn as a centered stroke along the background contour; defaults to null (no border)

alpha: @FloatRange(from = 0.0, to = 1.0) Float = DefaultAlpha

opacity applied to both fill and border, from 0.0f to 1.0f; defaults to 1.0f

BackgroundAnnotation

BackgroundAnnotation(
    colorProducer: ColorProducer,
    cornerRadius: Dp = DefaultCornerRadius,
    spread: BackgroundAnnotation.SpreadValues = DefaultSpread,
    mergeLines: Boolean = DefaultMergeLines,
    border: BackgroundAnnotation.Border? = null,
    alpha: @FloatRange(from = 0.0, to = 1.0) Float = DefaultAlpha
)

Creates a BackgroundAnnotation whose fill color is resolved lazily on each draw pass via colorProducer, enabling animations without relayout.

Parameters
colorProducer: ColorProducer

deferred color producer evaluated during the draw phase

cornerRadius: Dp = DefaultCornerRadius

radius applied to outer and inner corners of the contour; defaults to 0.dp. Coerced to at most half the length of the adjacent edge

spread: BackgroundAnnotation.SpreadValues = DefaultSpread

per-edge draw-phase spread applied to the range's bounding boxes (positive expands outward, negative shrinks inward); defaults to SpreadValues.Zero

mergeLines: Boolean = DefaultMergeLines

whether vertically adjacent overlapping boxes on consecutive lines join into a single contour (true) or draw as independent rounded rectangles (false); defaults to true

border: BackgroundAnnotation.Border? = null

optional Border drawn as a centered stroke along the background contour; defaults to null (no border)

alpha: @FloatRange(from = 0.0, to = 1.0) Float = DefaultAlpha

opacity applied to both fill and border, from 0.0f to 1.0f; defaults to 1.0f

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.

equals

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

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

hashCode

open fun hashCode(): Int

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

toString

open fun toString(): String

Public properties

alpha

val alpha: Float

opacity applied to both fill and border, from 0.0f to 1.0f; defaults to 1.0f

border

val border: BackgroundAnnotation.Border?

optional Border drawn as a centered stroke along the background contour (half of Border.width extends outside the contour and half overlaps inside the fill); defaults to null (no border)

brush

val brush: Brush?

fill brush drawn behind the annotated range, or null when constructed with color or colorProducer

color

val color: Color

fill color drawn behind the annotated range, or Color.Unspecified when constructed with colorProducer or brush

colorProducer

val colorProducer: ColorProducer?

deferred color producer evaluated during the draw phase, or null when constructed with color or brush

cornerRadius

val cornerRadius: Dp

radius applied to outer and inner corners of the contour; defaults to 0.dp. Coerced to at most half the length of the adjacent edge

mergeLines

val mergeLines: Boolean

whether vertically adjacent boxes on consecutive lines that overlap horizontally join into a single continuous contour (true) or draw as independent per-line rounded rectangles (false); defaults to true

spread

val spread: BackgroundAnnotation.SpreadValues

per-edge draw-phase spread applied to the range's bounding boxes (positive values expand outward, negative values shrink inward) without affecting text layout; defaults to SpreadValues.Zero. Any box or merged line stack whose resulting width or height is <= 0 is not drawn. See SpreadValues for per-box and multi-line behavior