Reputation: 23
I want to write this type of text ,is this possible?
Upvotes: 2
Views: 478
Reputation: 87824
Using Modifier.drawWithContent
and clipRect
you can draw only part of the contents of the view. Then you need to put two identical Text
in a Box
and draw the desired part of each view:
@Composable
fun TwoColorText(
text: String,
color1: Color,
color2: Color,
part: Float,
modifier: Modifier = Modifier,
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
) {
val textView = @Composable { color: Color, leftMultiplier: Float, rightMultiplier: Float ->
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 = onTextLayout,
style = style,
modifier = Modifier.drawWithContent {
clipRect(
left = size.width * leftMultiplier,
right = size.width * rightMultiplier
) {
[email protected]()
}
}
)
}
Box(modifier) {
textView(color1, 0f, part)
textView(color2, part, 1f)
}
}
Usage:
Row(Modifier.padding(10.dp)) {
TwoColorText(
"新鲜",
color1 = Color.Black,
color2 = Color.Red,
part = 0.27f,
)
Spacer(modifier = Modifier.width(50.dp))
TwoColorText(
"消息",
color1 = Color.Black,
color2 = Color.Red,
part = 0.27f,
)
}
Result:
Upvotes: 5