Jetpack Compose如何给Column添加除顶部外的三边边框?
在Jetpack Compose中给Column添加左、右、底部边框(去除顶部边框)
你可以通过自定义Modifier手动绘制需要的三条边框,替代默认的四边border方法,具体实现如下:
方法一:自定义绘制边框的Modifier
先创建一个扩展函数,通过drawWithContent来绘制左、右、底部的边框:
import androidx.compose.ui.Modifier import androidx.compose.ui.draw.drawWithContent import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.Size import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.Dp fun Modifier.leftRightBottomBorder(width: Dp, color: Color) = this.drawWithContent { // 先绘制Column的内容 drawContent() val borderWidthPx = width.toPx() // 绘制左边框 drawLine( color = color, start = Offset(0f, 0f), end = Offset(0f, size.height), strokeWidth = borderWidthPx ) // 绘制右边框 drawLine( color = color, start = Offset(size.width, 0f), end = Offset(size.width, size.height), strokeWidth = borderWidthPx ) // 绘制底部边框 drawLine( color = color, start = Offset(0f, size.height), end = Offset(size.width, size.height), strokeWidth = borderWidthPx ) }
在Column中使用该Modifier
把原来的.border()替换成自定义的leftRightBottomBorder即可:
Column( modifier = Modifier .weight(1f) .fillMaxWidth() .leftRightBottomBorder(2.dp, colorResource(R.color.appGreen)) ) { // 这里放置Column的内容 }
补充说明
这种方式可以精确控制每一条边框的显示,如果你需要调整边框的位置(比如让边框向内偏移),只需要修改绘制时的Offset参数即可。
内容的提问来源于stack exchange,提问作者juske
相关产品推荐
相关产品推荐

