我正在嘗試使用 Compose 實作此自定義形狀

但由于某種原因,分隔符偏移的圓圈是用虛線繪制的,這里是代碼
@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)
){}
}
}
誰能告訴我為什么用虛線繪制圓圈以及如何正確實作此形狀?
uj5u.com熱心網友回復:
您的圓未正確繪制,因為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)
}
})
}
結果:

uj5u.com熱心網友回復:
擺脫:
shape = DottedShape(step = 20.dp)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/345183.html
標籤:安卓 科特林 android-jetpack-compose android-jetpack
下一篇:美團的測驗面試題,真的很難嗎?
