[英]Image cropper with compose
我正在尝试用 compose 实现简单的图像裁剪器。 可以调整叠加层的大小并在图像上拖动。 问题是,它也可以被拖出图像和屏幕。 如何设置叠加层的限制以仅在图像上移动和调整大小?
更新的代码
@Composable
fun ImageCrooper() {
var size by remember { mutableStateOf(Size.Zero) }
var offsetX by remember { mutableStateOf(0f) }
var offsetY by remember { mutableStateOf(0f) }
var height by remember { mutableStateOf(140f) }
var width by remember { mutableStateOf(140f) }
BoxWithConstraints(
Modifier
.fillMaxWidth()
.height(240.dp)
.onSizeChanged {
size = it.toSize()
}
) {
Image(
modifier = Modifier
.fillMaxSize(),
contentScale = ContentScale.Crop,
painter = rememberAsyncImagePainter(
model = "https://i.picsum.photos/id/216/200/200.jpg?hmac=7Weas8POu49YrmUyJ6tWdqVMx-hw6lryzl8HnHZBzjc"
),
contentDescription = "A Content description",
)
BoxWithConstraints(
modifier = Modifier
.offset {
IntOffset(offsetX.roundToInt(), offsetY.roundToInt())
}
.height(height.dp)
.width(width.dp)
) {
// move the overlay
Box(
Modifier
.background(Color.Black.copy(0.6f))
.fillMaxSize()
.pointerInput(Unit) {
detectDragGestures { change, dragAmount ->
change.consumeAllChanges()
offsetY = (offsetY + dragAmount.y).coerceIn(0f, 230f)
offsetX = (offsetX + dragAmount.x).coerceIn(0f, size.width)
}
}
)
// resize the overlay
Box(
Modifier
.align(Alignment.BottomEnd)
.background(Color.White)
.height(20.dp)
.width(20.dp)
.pointerInput(Unit) {
detectDragGestures { change, dragAmount ->
change.consumeAllChanges()
width = (width + dragAmount.x).coerceIn(140f, size.width - width)
height = (height + dragAmount.y).coerceIn(140f, size.height - height)
}
}
)
}
}
}
您可以使用coerceIn
函数限制可组合尺寸范围内的偏移变量。 您可以使用获得可组合的大小
var size by remember { mutableStateOf(Size.Zero) }
Modifier.onSizeChanged {
size = it.toSize()
}
offsetY = (offsetY + dragAmount.y).coerceIn(0f, size.height)
offsetX = (offsetX + dragAmount.x).coerceIn(0f, size.width)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.