撰写:创建带有圆形背景的文本
来自 SwiftUI,我想创建一个视图Text,它有一个圆的背景,其中圆的宽度/高度随着里面的文本Text变长而增长。
因为Circle()Compose 中没有像 in 那样SwifUI,所以我只创建了一个Spacer并剪掉了它。下面的代码正在使用,ConstraintLayout因为我不知道如何获得宽度Text以将Circle可组合的大小设置为相同:
@Composable
fun CircleDemo() {
ConstraintLayout {
val (circle, text) = createRefs()
Spacer(
modifier = Modifier
.background(Color.Black)
.constrainAs(circle) {
centerTo(text)
}
)
Text(
text = "Hello",
color = Color.White,
modifier = Modifier
.constrainAs(text) {
centerTo(parent)
}
)
}
}
我可以使用一个mutableStateOf { 0 }我在onGloballyPositioned附加到的修饰符中更新它的地方Text,然后将其设置为requiredSizefor Spacer,但是 1. 这看起来很愚蠢,2.Spacer现在绘制在ConstraintLayout.
在视觉上我想实现这个:
我该怎么做呢?谢谢 :)
回答
随着1.0.x存在CircleShape。
您可以Text使用Box应用 aCircleShape作为背景来包装 ,并使用layout修饰符使 的尺寸适应Box当前文本。
就像是:
Box(contentAlignment= Alignment.Center,
modifier = Modifier
.background(Color.Black, shape = CircleShape)
.layout(){ measurable, constraints ->
// Measure the composable
val placeable = measurable.measure(constraints)
//get the current max dimension to assign width=height
val currentHeight = placeable.height
var heightCircle = currentHeight
if (placeable.width > heightCircle)
heightCircle = placeable.width
//assign the dimension and the center position
layout(heightCircle, heightCircle) {
// Where the composable gets placed
placeable.placeRelative(0, (heightCircle-currentHeight)/2)
}
}) {
Text(
text = "Hello World",
textAlign = TextAlign.Center,
color = Color.White,
modifier = Modifier.padding(4.dp).defaultMinSize(24.dp) //Use a min size for short text.
)
}