You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让可拖拽内容限制在Box Composable的边界内

实现拖拽范围限制在父Box边界内

要让蓝色小Box只能在父Box(300dp宽、200dp高)内拖拽,核心是获取父容器的实际尺寸,并在拖拽时约束子View的偏移量,确保其边缘不会超出父容器。以下是修正并实现功能的完整代码:

@Composable
private fun DraggableTextLowLevel() {
    Column(Modifier.fillMaxSize()) {
        Text("Custom Edit Place")
        // 父Box:300dp宽、200dp高,加背景方便查看边界
        Box(
            modifier = Modifier
                .height(200.dp)
                .width(300.dp)
                .background(Color.LightGray)
        ) {
            var offsetX by remember { mutableStateOf(0f) }
            var offsetY by remember { mutableStateOf(0f) }
            // 记录父Box的实际像素尺寸
            var parentSize by remember { mutableStateOf(IntSize.Zero) }
            // 子Box的固定尺寸(转成像素值)
            val childSize = with(LocalDensity.current) { 50.dp.toPx() }

            Box(
                Modifier
                    .offset { IntOffset(offsetX.roundToInt(), offsetY.roundToInt()) }
                    .background(Color.Blue)
                    .size(50.dp)
                    .pointerInput(Unit) {
                        detectDragGestures { change, dragAmount ->
                            change.consume()
                            // 计算新的偏移量
                            val newOffsetX = offsetX + dragAmount.x
                            val newOffsetY = offsetY + dragAmount.y
                            // 约束偏移范围:子Box完全在父Box内
                            offsetX = newOffsetX.coerceIn(0f, parentSize.width - childSize)
                            offsetY = newOffsetY.coerceIn(0f, parentSize.height - childSize)
                        }
                    }
            )

            // 监听父Box的尺寸变化
            Box(Modifier.matchParentSize().onSizeChanged { parentSize = it })
        }
    }
}

关键细节说明:

  • 获取父容器尺寸:通过matchParentSize()的辅助Box配合onSizeChanged,拿到父Box的实际像素尺寸,存在parentSize状态中。
  • 约束偏移范围:
    • 偏移量最小值设为0f,保证子Box左上角不会超出父Box左上角。
    • 偏移量最大值设为父容器尺寸 - 子Box尺寸,保证子Box右下角不会超出父Box右下角。
    • 用coerceIn方法快速实现范围约束,替代繁琐的if判断。
  • 修正原代码问题:修复了hieght拼写错误、语法括号问题,给父Box添加浅灰色背景方便直观确认边界。

内容的提问来源于stack exchange,提问作者Shiva s

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 09:32:49