如何在 Jetpack Compose 中制作虚线/虚线?

Phi*_*hov 2 android kotlin android-jetpack-compose

我需要从这个答案中复制 android XML 视图,但在 Jetpack Compose 中使用纯 kotlin

Phi*_*hov 5

您可以在 Jetpack Compose 中创建一个形状,如下所示:

private data class DottedShape(
    val step: Dp,
) : Shape {
    override fun createOutline(
        size: Size,
        layoutDirection: LayoutDirection,
        density: Density
    ) = Outline.Generic(Path().apply {
        val stepPx = with(density) { step.toPx() }
        val stepsCount = (size.width / stepPx).roundToInt()
        val actualStep = size.width / stepsCount
        val dotSize = Size(width = actualStep / 2, height = size.height)
        for (i in 0 until stepsCount) {
            addRect(
                Rect(
                    offset = Offset(x = i * actualStep, y = 0f),
                    size = dotSize
                )
            )
        }
        close()
    })
}
Run Code Online (Sandbox Code Playgroud)

用法:

Box(
    Modifier
        .height(1.dp)
        .fillMaxWidth()
        .background(Color.Gray, shape = DottedShape(step = 10.dp))
)
Run Code Online (Sandbox Code Playgroud)

结果:

在此处输入图片说明

  • @AminKeshavarzian 只需使用“Size(width = size.height, height = size.height)”重新定义 dotSize 并使用圆角矩形而不是普通矩形 (2认同)

Gab*_*tti 5

您可以简单地将 aCanvasdrawLine应用为pathEffecta的方法一起使用PathEffect.dashPathEffect

    val pathEffect = PathEffect.dashPathEffect(floatArrayOf(10f, 10f), 0f)
    Canvas(Modifier.fillMaxWidth().height(1.dp)) {

        drawLine(
            color = Color.Red,
            start = Offset(0f, 0f),
            end = Offset(size.width, 0f),
            pathEffect = pathEffect
        )
    }
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

您还可以将相同的 pathEffect 应用于其他方法:

    val stroke = Stroke(width = 2f,
      pathEffect = PathEffect.dashPathEffect(floatArrayOf(10f, 10f), 0f)
    )
    Canvas(Modifier.fillMaxWidth().height(70.dp)){
       drawRoundRect(color = Color.Red,style = stroke)
    }
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明