Modifier.border()
中没有参数可以实现虚线路径。
但是,您可以使用
DrawScope
使用 Path
绘制虚线 PathEffect.dashPathEffect
。
类似:
val stroke = Stroke(width = 2f,
pathEffect = PathEffect.dashPathEffect(floatArrayOf(10f, 10f), 0f)
)
drawBehind
修改器来绘制它:
Box(
Modifier
.size(250.dp,60.dp)
.drawBehind {
drawRoundRect(color = Color.Red, style = stroke)
},
contentAlignment = Alignment.Center
) {
Text(textAlign = TextAlign.Center,text = "Tap here to introduce yourseft")
}
如果你想要圆角,只需使用
cornerRadius
方法中的 drawRoundRect
属性:
drawRoundRect(color = Color.Red,style = stroke, cornerRadius = CornerRadius(8.dp.toPx()))
如果您愿意,可以使用上面相同的代码构建您的自定义
Modifier
。比如:
fun Modifier.dashedBorder(strokeWidth: Dp, color: Color, cornerRadiusDp: Dp) = composed(
factory = {
val density = LocalDensity.current
val strokeWidthPx = density.run { strokeWidth.toPx() }
val cornerRadiusPx = density.run { cornerRadiusDp.toPx() }
this.then(
Modifier.drawWithCache {
onDrawBehind {
val stroke = Stroke(
width = strokeWidthPx,
pathEffect = PathEffect.dashPathEffect(floatArrayOf(10f, 10f), 0f)
)
drawRoundRect(
color = color,
style = stroke,
cornerRadius = CornerRadius(cornerRadiusPx)
)
}
}
)
}
)
然后应用它:
Box(
Modifier
.size(250.dp,60.dp)
.dashedBorder(1.dp, Red, 8.dp),
contentAlignment = Alignment.Center
) {
Text(
text = "Tap here to introduce yourself",
textAlign = TextAlign.Center,
)
}
在对正常边框修改器进行一番挖掘后,我发现它使用 Stroke 对象,该对象可以接受一个参数 PathEffect ,可以使其成为虚线,这里是接受此参数的正常边框函数的修改版本。
https://gist.github.com/DavidIbrahim/236dadbccd99c4fd328e53587df35a21
我为修改器编写了这个扩展,您可以简单地使用它或修改它。
fun Modifier.dashedBorder(width: Dp, radius: Dp, color: Color) =
drawBehind {
drawIntoCanvas {
val paint = Paint()
.apply {
strokeWidth = width.toPx()
this.color = color
style = PaintingStyle.Stroke
pathEffect = PathEffect.dashPathEffect(floatArrayOf(10f, 10f), 0f)
}
it.drawRoundRect(
width.toPx(),
width.toPx(),
size.width - width.toPx(),
size.height - width.toPx(),
radius.toPx(),
radius.toPx(),
paint
)
}
}
@Composable
private fun AddNewFileButton(
modifier: Modifier = Modifier,
onClick: () -> Unit,
) {
val stroke = Stroke(
width = 4f,
pathEffect = PathEffect.dashPathEffect(floatArrayOf(10f, 10f), 0f)
)
Box(
modifier = modifier
.drawBehind {
drawRoundRect(
color = Color.Blue,
style = stroke,
cornerRadius = CornerRadius(16.dp.toPx())
)
}
.clip(RoundedCornerShape(16.dp))
.clickable { onClick() },
) {
Row(
modifier = modifier.padding(16.dp),
horizontalArrangement = Arrangement.Center
) {
Text(
text = "Add new item"
)
}
}
}