gpt4 book ai didi

android - 撰写 : Create Text with Circle Background

转载 作者:行者123 更新时间:2023-12-03 16:19:14 25 4
gpt4 key购买 nike

来自 SwiftUI,我想创建一个 Text 的 View 它有一个圆形的背景,圆形的宽度/高度随着Text中的文本而增长变得更长。
由于没有Circle()在 Compose 中,就像在 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 的修饰符然后将其设置为 requiredSize对于 Spacer , 但是 1. 这看起来很愚蠢 2. Spacer现在在 ConstraintLayout 的边界之外绘制.
视觉上我想实现这一点:
A black circle with the word Hello entered inside
我该怎么做呢?谢谢 :)

最佳答案

您可以使用 CircleShape .
您可以包装 TextBox申请 CircleShape作为背景并使用 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.
)
}
enter image description here

关于android - 撰写 : Create Text with Circle Background,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67134006/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com