It looks like a bug, I've created this issue.
Here's how you can restrict it manually:
@Composable
fun WrapTextContent(
text: String,
modifier: Modifier = Modifier,
color: Color = Color.Unspecified,
fontSize: TextUnit = TextUnit.Unspecified,
fontStyle: FontStyle? = null,
fontWeight: FontWeight? = null,
fontFamily: FontFamily? = null,
letterSpacing: TextUnit = TextUnit.Unspecified,
textDecoration: TextDecoration? = null,
textAlign: TextAlign? = null,
lineHeight: TextUnit = TextUnit.Unspecified,
overflow: TextOverflow = TextOverflow.Clip,
softWrap: Boolean = true,
maxLines: Int = Int.MAX_VALUE,
onTextLayout: (TextLayoutResult) -> Unit = {},
style: TextStyle = LocalTextStyle.current,
) {
SubcomposeLayout(modifier) { constraints ->
val composable = @Composable { localOnTextLayout: (TextLayoutResult) -> Unit ->
Text(
text = text,
color = color,
fontSize = fontSize,
fontStyle = fontStyle,
fontWeight = fontWeight,
fontFamily = fontFamily,
letterSpacing = letterSpacing,
textDecoration = textDecoration,
textAlign = textAlign,
lineHeight = lineHeight,
overflow = overflow,
softWrap = softWrap,
maxLines = maxLines,
onTextLayout = localOnTextLayout,
style = style,
)
}
var textWidthOpt: Int? = null
subcompose("measureView") {
composable { layoutResult ->
textWidthOpt = (0 until layoutResult.lineCount)
.maxOf { line ->
ceil(layoutResult.getLineRight(line) - layoutResult.getLineLeft(line)).toInt()
}
}
}[0].measure(constraints)
val textWidth = textWidthOpt!!
val placeable = subcompose("content") {
composable(onTextLayout)
}[0].measure(constraints.copy(minWidth = textWidth, maxWidth = textWidth))
layout(width = textWidth, height = placeable.height) {
placeable.place(0, 0)
}
}
}
Usage:
var textWidth by remember { mutableStateOf<Int?>(null) }
WrapTextContent(
"Box around text with a very very very very longlonglonglongword",
color = Color.White,
modifier = Modifier
.border(width = 2.dp, color = Color.Red)
.background(Color.DarkGray)
)
Result:
