【问题标题】:How to have dashed border in Jetpack Compose?如何在 Jetpack Compose 中有虚线边框?
【发布时间】:2021-03-01 18:27:58
【问题描述】:

我可以使用Modifier.border() 轻松创建普通边框,但如何创建虚线边框,如下图所示。

【问题讨论】:

    标签: android border android-jetpack-compose


    【解决方案1】:

    对于1.0.x,没有带有破折号路径的内置Modifier.border()

    但是,您可以在 Canvas 中使用 PathEffect.dashPathEffect
    比如:

    val stroke = Stroke(width = 2f,
        pathEffect = PathEffect.dashPathEffect(floatArrayOf(10f, 10f), 0f)
    )
    
    Box(Modifier.size(250.dp,60.dp),contentAlignment = Alignment.Center){
        Canvas(modifier = Modifier.fillMaxSize()) {
            drawRoundRect(color = Color.Red,style = stroke)
        }
        Text(
            textAlign = TextAlign.Center,text = "Tap here to introduce yourseft")
    }
    

    【讨论】:

    • 我不明白为什么不再有Modifier.border()?实际上我使用的是 android beta 04,它没有被弃用
    • @DavidIbrahim Modifier.border() 存在且未被弃用。
    • 哦,对不起,我误会了,我认为您正在为这个问题提供不同的解决方案,因为我的代码已被弃用,哈哈。
    【解决方案2】:

    在对普通边框修饰符进行了一些挖掘之后,我发现它使用了 Stroke 对象,该对象可以带一个参数 PathEffect 可以使其虚线,这里是一个修改采用此参数的普通边框函数的版本。

    https://gist.github.com/DavidIbrahim/236dadbccd99c4fd328e53587df35a21

    【讨论】:

    • 在上面的问题之后,我开始深入研究这个问题并被困在这个错误中:“类型不匹配:推断的类型是 DashPathEffect 但 PathEffect 是预期的。”这在 alpha-09 之前有效,但在 beta 上无效。在你的回答之后,我得到了它的工作。谢谢!
    【解决方案3】:

    我为修改器编写了这个扩展,你可以简单地使用它或修改它。

    fun Modifier.dashedBorder(width: Dp, radius: Dp, color: Color) = 
        drawBehind {
            drawIntoCanvas {
                val paint = Paint()
                    .apply {
                        strokeWidth = width.toPx()
                        this.color = color
                        style = PaintingStyle.Stroke
                        pathEffect = PathEffect.dashPathEffect(floatArrayOf(10f, 10f), 0f)
            }
            it.drawRoundRect(
                width.toPx(),
                width.toPx(),
                size.width - width.toPx(),
                size.height - width.toPx(),
                radius.toPx(),
                radius.toPx(),
                paint
            )
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-05
      • 2022-12-21
      • 1970-01-01
      • 2022-07-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多