Mark
10/17/2023, 4:33 AMval textMeasurer = rememberTextMeasurer()
val measureResult = textMeasurer.measure(
text = text,
style = TextStyle(
fontSize = fontSize,
fontFamily = fontFamily,
),
)
println("measuredSize: " + measureResult.size)
Text(
text = text,
color = color,
fontSize = fontSize,
fontFamily = fontFamily,
textAlign = TextAlign.Center,
modifier = Modifier
.wrapContentSize()
.drawWithCache {
println("actualSize: " + this.size)
onDrawWithContent {
drawContent()
}
}
,
)
Why is the actual size wider than the measured size?
measuredSize: 152 x 169
actualSize: Size(158.0, 169.0)
Note: text
is a single codepointephemient
10/17/2023, 4:47 AMLocalTextStyle.current.merge(fontSize = fontSize, fontFamily = fontFamily)
?Mark
10/17/2023, 4:49 AMHalil Ozercan
10/17/2023, 12:43 PMLocalTextStyle.current
which is the current TextStyle coming from MaterialTheme.
TextMeasurer on the other hand is a ui
class which has no concept of Material or theming whatsoever. So, it's crucial to use LocalTextStyle
to have the same result as Text composable.
I would also like to note that Text composable decides its color via LocalContentColor
in material3
, and LocalContentColor + LocalContentAlpha
in material
. So you may also need to take those into account if you want to draw the resulting TextLayoutResult
.Mark
10/18/2023, 8:51 AMstyle
argument (which defaults to LocalTextStyle.current
which is the current TextStyle coming from MaterialTheme)“?Huixing.Wang
10/18/2023, 11:26 AMHalil Ozercan
10/18/2023, 11:29 AMTextMeasurer
supports AnnotatedString
Huixing.Wang
10/19/2023, 2:30 AMHalil Ozercan
10/19/2023, 10:55 AMTextLayoutResult
has all the necessary functions to get the line metrics, indices where each line starts and ends, etc.Mark
10/19/2023, 1:00 PMHalil Ozercan
10/19/2023, 1:06 PMTextMeasurer
itself has an internal cache that's initialized with a default size of 8. So as long as your inputs to the measurement do not change, TextMeasurer
will skip the expensive text layout computation. Fortunately you can go even one step further and remember
the measurement result, completely skipping even the cache hit-miss detection. In short, it's not usually a major problem if you do the text layout once during composition.