You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Jetpack Compose Canvas中绘制带圆角的多边形(如圆角三角形)

Jetpack Compose Canvas 绘制圆角三角形实现方案

方案1:使用系统内置PathEffect(推荐,适合三个圆角大小一致的场景)

不需要修改原有路径逻辑,只需要在绘制时指定cornerPathEffect即可自动为所有边角添加圆角:

@Composable
fun RoundedTriangle(cornerRadius: Dp = 20.dp) {
    Canvas(modifier = Modifier.size(500.dp)) {
        val trianglePath = Path().apply {
            val height = size.height
            val width = size.width
            moveTo(width / 2.0f, 0f)
            lineTo(width, height)
            lineTo(0f, height)
            close() // 必须关闭路径,才能让底部两个角都生效圆角
        }
        drawPath(
            path = trianglePath,
            color = Color.Blue,
            pathEffect = PathEffect.cornerPathEffect(cornerRadius.toPx())
        )
    }
}

这个方案支持填充、描边等所有drawPath的样式配置,适配性强。

方案2:手动使用arcTo实现(适合需要自定义每个角圆角大小的场景)

如果需要三个角的圆角半径不同,可以手动计算每个顶点的切点和圆弧范围,自定义绘制:

@Composable
fun CustomRoundedTriangle(
    topRadius: Dp = 15.dp,
    bottomLeftRadius: Dp = 25.dp,
    bottomRightRadius: Dp = 30.dp
) {
    Canvas(modifier = Modifier.size(500.dp)) {
        val path = Path()
        val height = size.height
        val width = size.width
        val topR = topRadius.toPx()
        val blR = bottomLeftRadius.toPx()
        val brR = bottomRightRadius.toPx()

        // 顶角圆弧
        path.moveTo(width/2 + topR, 0f + topR * 0.5f)
        path.arcTo(
            rect = Rect(
                left = width/2 - topR,
                top = 0f,
                right = width/2 + topR,
                bottom = 2 * topR
            ),
            startAngleDegrees = 180f,
            sweepAngleDegrees = -180f,
            forceMoveTo = false
        )
        // 连接到右下角圆角起点
        path.lineTo(width - brR * 0.8f, height - brR * 0.6f)
        // 右下角圆弧
        path.arcTo(
            rect = Rect(
                left = width - 2 * brR,
                top = height - 2 * brR,
                right = width,
                bottom = height
            ),
            startAngleDegrees = -60f,
            sweepAngleDegrees = 60f,
            forceMoveTo = false
        )
        // 连接到左下角圆角起点
        path.lineTo(0f + blR * 0.8f, height - blR * 0.6f)
        // 左下角圆弧
        path.arcTo(
            rect = Rect(
                left = 0f,
                top = height - 2 * blR,
                right = 2 * blR,
                bottom = height
            ),
            startAngleDegrees = 120f,
            sweepAngleDegrees = 60f,
            forceMoveTo = false
        )
        path.close()

        drawPath(path, color = Color.Blue)
    }
}

手动实现时可以根据自己的圆角大小需求调整圆弧的角度和外接矩形参数,达到想要的效果。

内容的提问来源于stack exchange,提问作者Mohammad Derakhshan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 00:54:00