gpt4 book ai didi

android - 如何绘制用分隔线绘制的圆形边框描边?

转载 作者:行者123 更新时间:2023-12-05 00:10:26 25 4
gpt4 key购买 nike

我正在尝试使用 Compose 实现此自定义形状

Receipt image

但由于某些原因,分隔符偏移的圆圈用虚线绘制,这是代码

@Preview
@Composable
private fun ReceiptSeparator () {

Row(modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp) ,
verticalAlignment = Alignment.CenterVertically ,) {
Box(
modifier = Modifier
.requiredSize(50.dp)
.background(Color.White)
.offset(-40.dp)
.clip(CircleShape)
.border(BorderStroke(2.dp, Color.Gray))

){}

Box(
Modifier
.height(1.dp)
.requiredWidth(250.dp)
.weight(3f)
.background(Color.Gray, shape = DottedShape(step = 20.dp))
){}
Box(
modifier = Modifier

.offset(40.dp)
.clip(CircleShape)
.border(BorderStroke(2.dp, Color.Gray))
.background(Color.White)
.size(50.dp)
){}
}
}

为什么圆是用虚线画的,如何正确地画出这个形状?

最佳答案

你的圆没有正确绘制,因为 Modifier.border 默认绘制一个矩形边框,然后你用你的 Modifier.clip 剪辑它。相反,如果您需要将形状应用于边框,则需要将形状传递给 Modifier.border,如下所示:

.border(BorderStroke(2.dp, Color.Gray), shape = CircleShape)

但这并不能解决您的问题。要像图像中显示的那样正确绘制阴影,您需要将自定义形状应用于容器。

您可以使用 Modifier.onGloballyPositioned获取截止位置:

var separatorOffsetY by remember { mutableStateOf<Float?>(null) }
val cornerRadius = 20.dp
Card(
shape = RoundedCutoutShape(separatorOffsetY, cornerRadius),
backgroundColor = Color.White,
modifier = Modifier.padding(10.dp)
) {
Column {
Box(modifier = Modifier.height(200.dp))
Box(
Modifier
.padding(horizontal = cornerRadius)
.height(1.dp)
.requiredWidth(250.dp)
// DottedShape is taken from this answer:
// https://stackoverflow.com/a/68789205/3585796
.background(Color.Gray, shape = DottedShape(step = 20.dp))
.onGloballyPositioned {
separatorOffsetY = it.boundsInParent().center.y
}
)
Box(modifier = Modifier.height(50.dp))
}
}

使用此信息,您可以创建如下形状:

class RoundedCutoutShape(
private val offsetY: Float?,
private val cornerRadiusDp: Dp,
) : Shape {
override fun createOutline(
size: Size,
layoutDirection: LayoutDirection,
density: Density,
) = Outline.Generic(run path@{
val cornerRadius = with(density) { cornerRadiusDp.toPx() }
val rect = Rect(Offset.Zero, size)
val mainPath = Path().apply {
addRoundRect(RoundRect(rect, CornerRadius(cornerRadius)))
}
if (offsetY == null) return@path mainPath
val cutoutPath = Path().apply {
val circleSize = Size(cornerRadius, cornerRadius) * 2f
val visiblePart = 0.25f
val leftOval = Rect(
offset = Offset(
x = 0 - circleSize.width * (1 - visiblePart),
y = offsetY - circleSize.height / 2
),
size = circleSize
)
val rightOval = Rect(
offset = Offset(
x = rect.width - circleSize.width * visiblePart,
y = offsetY - circleSize.height / 2
),
size = circleSize
)
addOval(leftOval)
addOval(rightOval)
}
return@path Path().apply {
op(mainPath, cutoutPath, PathOperation.Difference)
}
})
}

结果:

关于android - 如何绘制用分隔线绘制的圆形边框描边?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69791009/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com