如何在用户按压时防止拖动



基本上我有一个ImageView可以zoomchange的垂直偏移量,但是当我想要缩放时,这真的很难做到,因为偏移量仍然是改变当打尖。

下面的代码:

modifier = Modifier
    .fillMaxSize()
    .background(Color.Black)
    .pointerInput(imageViewModel.currentZoom) {
        if (imageViewer.currentZoom == 1f) {
            detectDragGestures(
                onDragStart = { imageViewModel.isPressed = true },
                onDragEnd = { imageViewModel.isPressed = false },
                onDragCancel = { imageViewModel.isPressed = false },
                onDrag = { change, dragAmount ->
                    change.consumeAllChanges()
                    // TODO: if (fingerCount == 1) or when there is no multitouch detected
                    // change the offset by drag amount
                    imageViewModel.offsetY += dragAmount.y
                }
            )
        }
    }

我自己找到了一个解决方案,这是修改后的方案:

val fingerCount = remember { 0f }
modifier = Modifier
    .fillMaxSize()
    .background(Color.Black)
    .pointerInput(Unit) {
        forEachGesture {
            val context = currentCoroutineContext()
            awaitPointerEventScope {
                do {
                    val event = awaitPointerEvent()
                    fingerCount = event.changes.size
                } while (event.changes.any { it.pressed } && context.isActive)
            }
        }
    }
    .pointerInput(
        key1 = imageViewModel.currentZoom,
        key2 = fingerCount,
    ) {
        if (imageViewModel.offsetY != 0f || fingerCount > 1) {
            imageViewModel.isPressed = false
        }
        if (imageViewer.currentZoom == 1f) {
            detectDragGestures(
                onDragStart = { imageViewModel.isPressed = true },
                onDragEnd = { imageViewModel.isPressed = false },
                onDragCancel = { imageViewModel.isPressed = false },
                onDrag = { change, dragAmount ->
                    if ((fingerCount == 1 || imageViewModel.offsetY != 0f) && sheetState.targetValue == ModalBottomSheetValue.Hidden) {
                        change.consumeAllChanges()
                        imageViewModel.offsetY += dragAmount.y
                    }
                }
            )
        }
    }
    .offset {
        IntOffset(
            x = 0,
            y =
            if (imageViewModel.isPressed)
                imageViewModel.offsetY.roundToInt()
            else
                animatedOffsetY.roundToInt(),
        )
    },

最新更新