作为Box的替代方法,您可以使用自定义布局
@Composable
fun OverlappingBoxes(
modifier: Modifier = Modifier,
content: @Composable () -> Unit,
) {
Layout(
modifier = modifier,
content = content,
) { measurables, constraints ->
val largeBox = measurables[0]
val smallBox = measurables[1]
val looseConstraints = constraints.copy(
minWidth = 0,
minHeight = 0,
)
val largePlaceable = largeBox.measure(looseConstraints)
val smallPlaceable = smallBox.measure(looseConstraints)
layout(
width = constraints.maxWidth,
height = largePlaceable.height + smallPlaceable.height / 2,
) {
largePlaceable.placeRelative(
x = 0,
y = 0,
)
smallPlaceable.placeRelative(
x = - smallPlaceable.width / 2, // overlap by exactly half the sise of second box x axis wise
y = largePlaceable.height / 2 - smallPlaceable.height / 2 //center with y axis
)
}
}
}
@Composable
fun BoxOverlap(
modifier: Modifier = Modifier,
) {
OverlappingBoxes(modifier = modifier.size(300.dp)) {
Box(
modifier = Modifier
.size(300.dp)
.background(Color.Green)
) {
}
Box(
modifier = Modifier
.size(100.dp)
.clip(RoundedCornerShape(16.dp))
.background(Color.Blue)
) {
}
}
}
如果您希望第二个框偏移基于百分比
val percentageFromTop = 0.3f // 30% from the top
val yOffset = (largePlaceable.height * percentageFromTop).roundToInt()
smallPlaceable.placeRelative(x = - smallPlaceable.width / 2,y = yOffset - smallPlaceable.height / 2
)
在使用约束布局的情况下还有其他答案Overlap two Box jetpack compose.但是,如果您想使用百分比,您可以使用自定义布局