【问题标题】:Compose: Create Text with Circle Background撰写:创建带有圆形背景的文本
【发布时间】:2021-04-17 01:59:08
【问题描述】:

来自 SwiftUI,我想创建一个 Text 的视图,其中它具有圆形背景,其中圆形的宽度/高度随着 Text 内的文本变长而增长。

因为 Compose 中没有 Circle(),就像 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 },我在附加到TextonGloballyPositioned 修饰符中对其进行更新,然后将其设置为SpacerrequiredSize,但是1. 这看起来很愚蠢,2. Spacer 现在在 ConstraintLayout 的边界之外绘制。

视觉上我想实现这个:

我该怎么做呢?谢谢你:)

【问题讨论】:

    标签: android android-jetpack-compose android-jetpack-compose-text


    【解决方案1】:

    您可以使用CircleShape
    您可以用Box 包裹Text,应用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.
        )
    }
    

    【讨论】:

    • 谢谢,对于像“Hello World”这样较长的字符串效果很好,但我不确定需要什么才能使它适用于“1”
    • @Benoit 只需将 minSize 分配给 Text 元素。例如.defaultMinSize(24.dp)
    • @GabrieleMariotti for small string 效果不佳,即使给出 minSize。
    【解决方案2】:

    使用透明颜色内的黑色圆圈的背景可绘制。背景可绘制对象将拉伸以填充视图,而圆形应很好地拉伸而不会产生伪影。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-08
      • 1970-01-01
      • 2018-03-15
      • 1970-01-01
      • 2019-12-21
      • 1970-01-01
      • 2023-03-19
      • 1970-01-01
      相关资源
      最近更新 更多