Jetpack Compose中如何实现内圆角效果?
实现内圆角(反向圆角)效果的方案
CutCornerShape仅支持直角切角,要实现图中的内凹圆角效果,你可以通过以下两种方式实现:
方法一:自定义Shape类
创建一个继承自Shape的自定义类,通过Path绘制内凹圆角的轮廓:
class InnerRoundedCornerShape( private val cornerRadius: Dp ) : Shape { override fun createOutline( size: Size, layoutDirection: LayoutDirection, density: Density ): Outline { val radius = with(density) { cornerRadius.toPx() } val path = Path().apply { // 绘制左上角内凹圆角 moveTo(0f, radius) arcTo( rect = Rect(0f, 0f, radius * 2, radius * 2), startAngleDegrees = 180f, sweepAngleDegrees = 90f, forceMoveTo = false ) // 顶部边 lineTo(size.width - radius, 0f) // 右上角内凹圆角 arcTo( rect = Rect(size.width - radius * 2, 0f, size.width, radius * 2), startAngleDegrees = 270f, sweepAngleDegrees = 90f, forceMoveTo = false ) // 右侧边 lineTo(size.width, size.height - radius) // 右下角内凹圆角 arcTo( rect = Rect(size.width - radius * 2, size.height - radius * 2, size.width, size.height), startAngleDegrees = 0f, sweepAngleDegrees = 90f, forceMoveTo = false ) // 底部边 lineTo(radius, size.height) // 左下角内凹圆角 arcTo( rect = Rect(0f, size.height - radius * 2, radius * 2, size.height), startAngleDegrees = 90f, sweepAngleDegrees = 90f, forceMoveTo = false ) close() } return Outline.Generic(path) } }
使用示例:
Box( modifier = Modifier .size(200.dp) .background(Color.Blue, shape = InnerRoundedCornerShape(30.dp)) )
方法二:直接通过drawBehind绘制
无需自定义Shape,直接在Modifier.drawBehind中绘制内凹圆角背景:
Box( modifier = Modifier .size(200.dp) .drawBehind { val radius = 30.dp.toPx() val path = Path().apply { moveTo(0f, radius) arcTo(Rect(0f, 0f, radius * 2, radius * 2), 180f, 90f, false) lineTo(size.width - radius, 0f) arcTo(Rect(size.width - radius*2, 0f, size.width, radius*2), 270f, 90f, false) lineTo(size.width, size.height - radius) arcTo(Rect(size.width - radius*2, size.height - radius*2, size.width, size.height), 0f, 90f, false) lineTo(radius, size.height) arcTo(Rect(0f, size.height - radius*2, radius*2, size.height), 90f, 90f, false) close() } drawPath(path, color = Color.Blue) } )
如果需要为不同角设置不同的内圆角大小,可以修改自定义Shape的参数,添加单独的圆角配置,逻辑和RoundedCornerShape类似。
内容的提问来源于stack exchange,提问作者Svilen Rusev
相关产品推荐
相关产品推荐

