在 Android 中仅在描边线的一端应用上限

Applying cap on only one end of a stroked line in Android

在 Compose Canvas DrawScope 上下文中绘图时,是否可以仅将笔划的两端之一应用到笔画的两端?

没有内置解决方案。

我也找不到 android.graphics.Canvas 的解决方案:如果您知道如何在 android canvas 中简单地做到这一点,您可以在 [=12] 的 compose c 中使用它=].

我能想到的唯一方法是在上面画上盖子:

fun DrawScope.drawLine(
    color: Color,
    start: Offset,
    end: Offset,
    strokeWidth: Float = Stroke.HairlineWidth,
    startCap: StrokeCap,
    endCap: StrokeCap,
) {
    drawLine(
        color = color,
        start = start,
        end = end,
        strokeWidth = strokeWidth,
        cap = StrokeCap.Butt,
    )
    listOf(
        Triple(start, end, startCap),
        Triple(end, start, endCap),
    ).forEach {
        drawCap(
            color = color,
            start = it.first,
            end = it.second,
            strokeWidth = strokeWidth,
            cap = it.third
        )
    }
}

private fun DrawScope.drawCap(
    color: Color,
    start: Offset,
    end: Offset,
    strokeWidth: Float = Stroke.HairlineWidth,
    cap: StrokeCap,
) {
    when (cap) {
        StrokeCap.Butt -> Unit
        StrokeCap.Round -> {
            drawCircle(color, center = start, radius = strokeWidth / 2)
        }
        StrokeCap.Square -> {
            val offset = Offset(strokeWidth / 2, strokeWidth / 2)
            val size = Size(strokeWidth, strokeWidth)

            rotateRad(
                radians = (end - start).run { atan2(x, y) },
                pivot = start
            ) {
                drawRect(color, topLeft = start - offset, size = size)
            }
        }
    }
}

计算 StrokeCap.Square 中直线的角度非常简单,但如果您需要曲线,解决方案可能并不那么容易。

但是在你只需要支持StrokeCap.Round知道start/end点和笔画宽度就足够了。