如何仅在jetpack compose中在底部添加边框

时间:2021-07-30 14:26:03

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

我想在布局的底部添加边框。我知道我可以使用 Divider 可组合,但我只想学习如何绘制边框

目前我可以为所有边添加边框,这不是我想要的

Row(modifier = Modifier.border(border = BorderStroke(width = 1.dp,Color.LightGray))) {
                TextField(value = "", onValueChange = {}, modifier = Modifier.weight(1f))
                Switch(checked = true, onCheckedChange = {})
                Icon(Icons.Filled.Close, "Remove", tint = Color.Gray)
            }

3 个答案:

答案 0 :(得分:0)

您可以在绘图范围内画一条线。在我看来,分隔符在代码中看起来更简洁。

Row(modifier = Modifier
  .drawWithContent {
    drawContent()
    clipRect { // Not needed if you do not care about painting half stroke outside
      val strokeWidth = Stroke.DefaultMiter
      val y = size.height // - strokeWidth 
          // if the whole line should be inside component
      drawLine(
        brush = SolidColor(Color.Red),
        strokeWidth = strokeWidth,
        cap = StrokeCap.Square,
        start = Offset.Zero.copy(y = y),
        end = Offset(x = size.width, y = y)
      )
    }
  }
) {
  Text("test")
}

答案 1 :(得分:0)

您可以使用 drawBehind 修饰符。
类似的东西:

Row(
    modifier = Modifier
        .drawBehind {
            val strokeWidth = indicatorWidth.value * density
            val y = size.height - strokeWidth / 2

            drawLine(
                Color.LightGray,
                Offset(0f, y),
                Offset(size.width, y),
                strokeWidth
            )
        }){
    //....
}

enter image description here

答案 2 :(得分:0)

是的,应该这样做:-

@Suppress("UnnecessaryComposedModifier")
fun Modifier.topRectBorder(width: Dp = Dp.Hairline, brush: Brush = SolidColor(Color.Black)): Modifier = composed(
    factory = {
        this.then(
            Modifier.drawWithCache {
                onDrawWithContent {
                    drawContent()
                    drawLine(brush, Offset(width.value, 0f), Offset(size.width - width.value, 0f))
                }
            }
        )
    },
    inspectorInfo = debugInspectorInfo {
        name = "border"
        properties["width"] = width
        if (brush is SolidColor) {
            properties["color"] = brush.value
            value = brush.value
        } else {
            properties["brush"] = brush
        }
        properties["shape"] = RectangleShape
    }
)

相关问题