gpt4 book ai didi

android - 如何在 Jetpack Compose 中限制图像平移到框的边缘?

转载 作者:行者123 更新时间:2023-12-03 08:07:17 24 4
gpt4 key购买 nike

如何在 Compose 中限制图像平移到框的边缘?

我使用 pointerInput(Unit) { detectorTransformGestures { centroid, pan, Zoom,rotation -> }} 来控制缩放和平移。

当使用 if (scale.value == 1f) 0f else panOffsetX 将图像最小化到 1f 时,我正在解决此平移问题。我想对放大的图像执行相同的操作 (1f < scale <= 3f)

Box(
modifier = Modifier
.clip(RectangleShape)
.fillMaxWidth()
.background(Color.Gray)
.pointerInput(Unit) {
detectTransformGestures { centroid, pan, zoom, rotation ->
val constraintZoom = when {
scale.value > 3f -> 3f
scale.value < 1f -> 1f
else -> (scale.value * zoom)
}
scale.value = constraintZoom
panOffset += pan
panOffsetX += pan.x
panOffsetY += pan.y
centroidOffset = centroid
rotationState.value += rotation
}
}
) {
Image(
modifier = Modifier
.align(Alignment.Center)
.graphicsLayer(
scaleX = maxOf(1f, minOf(3f, scale.value)),
scaleY = maxOf(1f, minOf(3f, scale.value)),
translationX = if (scale.value == 1f) 0f else panOffsetX,
translationY = if (scale.value == 1f) 0f else panOffsetY,
),
contentDescription = null,
painter = painterResource(R.drawable.my_sample_image)
)
}

最佳答案

技巧是使用您的可组合大小和缩放级别来限制它

val maxX = (size.width * (zoom - 1) / 2f)
val maxY = (size.height * (zoom - 1) / 2f)

offset = newOffset
offset = Offset(
newOffset.x.coerceIn(-maxX, maxX),
newOffset.y.coerceIn(-maxY, maxY)

全面实现

var zoom by remember { mutableStateOf(1f) }
var offset by remember { mutableStateOf(Offset.Zero) }
var size by remember { mutableStateOf(IntSize.Zero) }

修饰符

  val imageModifier = Modifier
.fillMaxSize()
.aspectRatio(4 / 3f)
.clipToBounds()
.pointerInput(Unit) {
detectTransformGestures(
onGesture = { _, gesturePan, gestureZoom, _ ->

zoom = (zoom * gestureZoom).coerceIn(1f, 3f)
val newOffset = offset + gesturePan.times(zoom)

val maxX = (size.width * (zoom - 1) / 2f)
val maxY = (size.height * (zoom - 1) / 2f)

offset = Offset(
newOffset.x.coerceIn(-maxX, maxX),
newOffset.y.coerceIn(-maxY, maxY)
)
}
)
}
.onSizeChanged {
size = it
}
.graphicsLayer {
translationX = offset.x
translationY = offset.y
scaleX = zoom
scaleY = zoom
}

关于android - 如何在 Jetpack Compose 中限制图像平移到框的边缘?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71810485/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com