[英]Prevent dragging box out of the screen with Jetpack Compose
我从这里有这样的代码: https://developer.android.com/jetpack/compose/gestures
Box(modifier = Modifier.fillMaxSize()) {
var offsetX by remember { mutableStateOf(0f) }
var offsetY by remember { mutableStateOf(0f) }
Box(
Modifier
.offset { IntOffset(offsetX.roundToInt(), offsetY.roundToInt()) }
.background(Color.Red)
.size(120.dp) // makes it rectangle. wrap_content without it
.align(Alignment.BottomEnd)
.pointerInput(Unit) {
detectDragGestures { change, dragAmount ->
change.consume()
offsetX += dragAmount.x
offsetY += dragAmount.y
}
}
) {
// todo
}
}
所以对于x
的end
,我创建了这样的东西:
val newOffsetX = if ((offsetX + dragAmount.x) < 0) { offsetX + dragAmount.x } else { 0 }
offsetX = newOffsetX
但是我怎样才能找到x
的start
并防止我的可拖动框 go 超出屏幕? 有没有办法为X
和Y
做到这一点?
如果将可拖动框与Alignment.TopStart
对齐,则可以强制最小和最大宽度和高度介于 0 和父尺寸之间 - 盒子尺寸
@Composable
private fun DragSample() {
BoxWithConstraints(modifier = Modifier.fillMaxSize()) {
var offsetX by remember { mutableStateOf(0f) }
var offsetY by remember { mutableStateOf(0f) }
val parentWidth = constraints.maxWidth
val parentHeight = constraints.maxHeight
Box(
Modifier
.offset { IntOffset(offsetX.roundToInt(), offsetY.roundToInt()) }
.background(Color.Red)
.size(120.dp) // makes it rectangle. wrap_content without it
.align(Alignment.TopStart)
.pointerInput(Unit) {
val boxSize = this.size
detectDragGestures { _, dragAmount ->
offsetX = (offsetX + dragAmount.x).coerceIn(
0f,
parentWidth - boxSize.width.toFloat()
)
offsetY = (offsetY + dragAmount.y).coerceIn(
0f,
parentHeight - boxSize.height.toFloat()
)
}
}
) {
// todo
}
}
}
如果你想从Alignemnt.BottomEnd
开始,你应该这样做
@Composable
private fun DragSample() {
BoxWithConstraints(modifier = Modifier.fillMaxSize()) {
var offsetX by remember { mutableStateOf(0f) }
var offsetY by remember { mutableStateOf(0f) }
val parentWidth = constraints.maxWidth
val parentHeight = constraints.maxHeight
Box(
Modifier
.offset { IntOffset(offsetX.roundToInt(), offsetY.roundToInt()) }
.background(Color.Red)
.size(120.dp) // makes it rectangle. wrap_content without it
.align(Alignment.BottomEnd)
.pointerInput(Unit) {
val boxSize = this.size
detectDragGestures { _, dragAmount ->
offsetX = (offsetX + dragAmount.x).coerceIn(
boxSize.width.toFloat() -parentWidth,
0f
)
offsetY = (offsetY + dragAmount.y).coerceIn(
boxSize.height.toFloat() -parentHeight,
0f
)
}
}
) {
// todo
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.