Pit*_*tos 2 android android-jetpack-compose android-jetpack-compose-gesture
如何在 Compose 中限制图像平移到框的边缘?
我用来pointerInput(Unit) { detectTransformGestures { centroid, pan, zoom, rotation -> }}控制缩放和平移。
当图像最小化为 时,我正在解决这个平移1f问题if (scale.value == 1f) 0f else panOffsetX。我想对放大的图像执行相同的操作(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)
)
}
Run Code Online (Sandbox Code Playgroud)

技巧是使用您的可组合大小和缩放级别来限制它
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)
Run Code Online (Sandbox Code Playgroud)
全面实施
状态
var zoom by remember { mutableStateOf(1f) }
var offset by remember { mutableStateOf(Offset.Zero) }
var size by remember { mutableStateOf(IntSize.Zero) }
Run Code Online (Sandbox Code Playgroud)
修饰符
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
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
575 次 |
| 最近记录: |