AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • 主页
  • 系统&网络
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • 主页
  • 系统&网络
    • 最新
    • 热门
    • 标签
  • Ubuntu
    • 最新
    • 热门
    • 标签
  • Unix
    • 最新
    • 标签
  • DBA
    • 最新
    • 标签
  • Computer
    • 最新
    • 标签
  • Coding
    • 最新
    • 标签
主页 / coding / 问题 / 79146556
Accepted
joepetrakovich
joepetrakovich
Asked: 2024-11-01 07:05:48 +0800 CST2024-11-01 07:05:48 +0800 CST 2024-11-01 07:05:48 +0800 CST

如何在拖动过程中保持视图以用户手指为中心

  • 772

我有一个光标图标,我想让它在用户拖动它时保持在用户手指的中心,但是由于触摸误差和其他各种原因,它不能通过 onDrag 中的拖动量简单地更新视图的偏移量来保持中心位置。

我以为我可以计算触摸点的全局 XY 并将其设置为该值,但如果不执行诸如使用 pointerInterop 修饰符之类的令人沮丧的操作,则很难在 Compose 中获取该值。

     onDrag = { change, dragAmount ->
                    change.consume()

                    params.x += dragAmount.x.toInt()
                    params.y += dragAmount.y.toInt()
                    wm.updateViewLayout(composeView, params)
                   
                }

更新 1

肯定有一些明显的数学知识我没注意到。我能够通过将视图按偏移量移动,将视图的中心点与用户在 DragStart 上的手指同步,如下所示:

onDragStart = {
    params.x = params.x + it.x.toInt() - (composeView.width / 2)
    params.y = params.y + it.y.toInt() - (composeView.height / 2)
    wm.updateViewLayout(composeView, params)
},
onDrag = { change, dragAmount ->
    change.consume()
    //cant do that here though so doing the normal way below
    // params.x = params.x + change.position.x.toInt() - (composeView.width / 2)
    // params.y = params.y + change.position.y.toInt() - (composeView.height / 2)
    params.x += dragAmount.x.toInt()
    params.y += dragAmount.y.toInt()
   
    wm.updateViewLayout(composeView, params)
}

如果我注释掉 dragamount 增量方式并使用调整后的方式,拖动它时它会变得不稳定,疯狂地跳来跳去。

我尝试了一些其他技术,例如使用awaitEachGesture(如下所示)drag来摆脱触摸倾斜检测,但这并没有让我更接近目标。
真正的问题似乎发生在用户拖动速度非常慢的时候。如果你拖动得非常慢,出于某种原因,你的手指就会从视图中移开。这就像视图对非常微小的移动没有​​反应一样。
我想要做的就是让视图保持在触摸点的中心。这似乎应该只是一些具有现有可用参数的公式。

 .pointerInput(Unit) {
                awaitEachGesture {
                    val down = awaitFirstDown()

                    drag(down.id) { change ->
                        val posChange = change.positionChange()
                        val pos = change.position
                        Log.i("await gesture drag", "change: ${pos}")
                        Log.i("await gesture drag", "poschange: ${posChange}")
                        change.consume()
                        params.x += posChange.x.toInt()
                        params.y += posChange.y.toInt()
                       // params.x = params.x + pos.x.toInt() - (composeView.width / 2)
                       // params.y = params.y + pos.y.toInt() - (composeView.height / 2)
                        wm.updateViewLayout(composeView, params)
                    }

                }
            }

我还制作了此 GIF 来展示问题。首先,您可以看到,即使我移动得很快,触摸点也会有一些漂移。它会移到圆圈的边缘。更糟糕的是,如果我移动得非常慢,它会漂移很多。

更新 2

我刚刚意识到这可能是因为布局参数 x 和 y 的拖动量必须四舍五入为整数。我明天会调查一下。

imgur 问题的 GIF

更新 3

我关于舍入的理论是正确的。当您非常缓慢地拖动时,更改位置/拖动量浮点.toInt()会向下舍入为零,并且不会造成任何移动。将其更改为roundToInt也不起作用,因为缓慢的移动会在向上舍入时慢慢爬过您的手指。对我来说,解决方案是使用浮点累加器,这样小的拖动量就不会被吞没。我猜这是因为我围绕父 ComposeView 移动,而不是从触摸元素自己的.offset修饰符移动?我不太确定有什么区别,因为我知道您不需要通常的拖动技术累加器,也许引擎盖下有一个隐藏的累加器?

            .pointerInput(Unit) {

                val center = size.center

                awaitEachGesture {
                    val down = awaitFirstDown()

                    params.x += (down.position.x - center.x).roundToInt()
                    params.y += (down.position.y - center.y).roundToInt() 
                    wm.updateViewLayout(composeView, params)

                    drag(down.id) { change ->
                        val posChange = change.positionChange()

                        change.consume()

                        accumulatedX += posChange.x
                        accumulatedY += posChange.y

                        val deltaX = accumulatedX.toInt()
                        val deltaY = accumulatedY.toInt()

                        accumulatedX -= deltaX
                        accumulatedY -= deltaY

                        params.x += deltaX
                        params.y += deltaY
                        wm.updateViewLayout(composeView, params)
                    }

                }
            }
android-jetpack-compose
  • 1 1 个回答
  • 62 Views

1 个回答

  • Voted
  1. Best Answer
    Thracian
    2024-11-01T12:52:52+08:002024-11-01T12:52:52+08:00

    如果可以在父级上添加触摸手势,您可以检查触摸位置是否在您的 composeView 中,并检查拖动是否

    结果

    在此处输入图片描述

    @Preview
    @Composable
    fun DragFromCenterTest() {
    
        var offset by remember {
            mutableStateOf(Offset.Zero)
        }
    
        var childSize by remember {
            mutableStateOf(IntSize.Zero)
        }
    
        var isTouched by remember {
            mutableStateOf(false)
        }
        Box(
            modifier = Modifier.fillMaxSize()
    
                .pointerInput(Unit) {
    
                    awaitEachGesture {
                        val down = awaitFirstDown()
    
                        val position = down.position
                        isTouched = position.minus(offset)
                            .getDistanceSquared() < childSize.width * childSize.width
                        do {
    
                            //This PointerEvent contains details including
                            // event, id, position and more
                            val event: PointerEvent = awaitPointerEvent()
    
                            event.changes.firstOrNull()?.let { pointerInputChange ->
                                if (isTouched) {
    
                                    val position = pointerInputChange.position
                                    
                                    offset =
                                        Offset(
                                            position.x - childSize.width / 2,
                                            position.y - childSize.height / 2
                                        )
                                }
                            }
    
    
                        } while (event.changes.any { it.pressed })
                    }
    
                    // Alternative 2 with drag
    //                detectDragGestures(
    //                    onDragStart = { position ->
    //                         isTouched = position.minus(offset)
    //                            .getDistanceSquared() < childSize.width * childSize.width
    //
    //                        if (isTouched) {
    //                            offset =
    //                                Offset(
    //                                    position.x - childSize.width / 2,
    //                                    position.y - childSize.height / 2
    //                                )
    //                        }
    //                    },
    //                    onDrag = { change, dragAmount ->
    //
    //                        val position = change.position
    //
    //                        if (isTouched) {
    //                            offset =
    //                                Offset(
    //                                    position.x - childSize.width / 2,
    //                                    position.y - childSize.height / 2
    //                                )
    //                        }
    //                    }
    //                )
                }
        ) {
    
            Draggable(
                modifier = Modifier
                    .onSizeChanged {
                        childSize = it
                    }
                    .offset {
                        IntOffset(offset.x.toInt(), offset.y.toInt())
                    }
                    .drawWithContent {
                        drawContent()
                        drawCircle(
                            color = Color.Red,
                            radius = 10.dp.toPx()
                        )
                    }
            )
        }
    }
    
    @Composable
    fun Draggable(
        modifier: Modifier,
    ) {
        Box(modifier.size(100.dp).background(Color.Blue, CircleShape))
    }
    

    如果您希望向子项添加手势,则需要计算第一次触摸到 Composable 中心的距离,如下所示

    @Preview
    @Composable
    fun DragFromCenterTest2() {
    
        var offset by remember {
            mutableStateOf(Offset.Zero)
        }
    
        Box(
            modifier = Modifier.fillMaxSize()
        ) {
    
            Draggable(
                modifier = Modifier
    
                    .offset {
                        IntOffset(offset.x.toInt(), offset.y.toInt())
                    }
    
                    .pointerInput(Unit) {
    
                        val size = size
                        val center = size.center
                        awaitEachGesture {
    
                            val down = awaitFirstDown()
    
                            val firstDown = down.position
    
                            val distanceToCenter =
                                Offset(firstDown.x - center.x, firstDown.y - center.y)
                            // Move current position to first down position to center it at first
                            // touch position
                            offset += distanceToCenter
    
                            do {
    
                                val event: PointerEvent = awaitPointerEvent()
    
                                event.changes.firstOrNull()?.let { pointerInputChange ->
    
                                    val position = pointerInputChange.positionChange()
    
                                    offset += position
    
                                }
    
                            } while (event.changes.any { it.pressed })
                        }
                    }
                    .drawWithContent {
                        drawContent()
                        drawCircle(
                            color = Color.Red,
                            radius = 10.dp.toPx()
                        )
                    }
            )
        }
    }
    
    • 1

相关问题

  • 在jetpack compose中绘制容器边界外

  • 为什么 Jetpack Compose 在 onTap 事件中使用旧状态

  • 在 Jetpack Compose 中单独为每个字母设置动画时将画笔效果应用于整个单词

  • 将 StateFlow 设置为 null 时,Jetpack Compose 中的 Canvas 不清除绘制内容的问题

  • 如何在 Jetpack Compose 中制作钢琴音符?

Sidebar

Stats

  • 问题 205573
  • 回答 270741
  • 最佳答案 135370
  • 用户 68524
  • 热门
  • 回答
  • Marko Smith

    Vue 3:创建时出错“预期标识符但发现‘导入’”[重复]

    • 1 个回答
  • Marko Smith

    为什么这个简单而小的 Java 代码在所有 Graal JVM 上的运行速度都快 30 倍,但在任何 Oracle JVM 上却不行?

    • 1 个回答
  • Marko Smith

    具有指定基础类型但没有枚举器的“枚举类”的用途是什么?

    • 1 个回答
  • Marko Smith

    如何修复未手动导入的模块的 MODULE_NOT_FOUND 错误?

    • 6 个回答
  • Marko Smith

    `(表达式,左值) = 右值` 在 C 或 C++ 中是有效的赋值吗?为什么有些编译器会接受/拒绝它?

    • 3 个回答
  • Marko Smith

    何时应使用 std::inplace_vector 而不是 std::vector?

    • 3 个回答
  • Marko Smith

    在 C++ 中,一个不执行任何操作的空程序需要 204KB 的堆,但在 C 中则不需要

    • 1 个回答
  • Marko Smith

    PowerBI 目前与 BigQuery 不兼容:Simba 驱动程序与 Windows 更新有关

    • 2 个回答
  • Marko Smith

    AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String”

    • 1 个回答
  • Marko Smith

    我正在尝试仅使用海龟随机和数学模块来制作吃豆人游戏

    • 1 个回答
  • Martin Hope
    Aleksandr Dubinsky 为什么 InetAddress 上的 switch 模式匹配会失败,并出现“未涵盖所有可能的输入值”? 2024-12-23 06:56:21 +0800 CST
  • Martin Hope
    Phillip Borge 为什么这个简单而小的 Java 代码在所有 Graal JVM 上的运行速度都快 30 倍,但在任何 Oracle JVM 上却不行? 2024-12-12 20:46:46 +0800 CST
  • Martin Hope
    Oodini 具有指定基础类型但没有枚举器的“枚举类”的用途是什么? 2024-12-12 06:27:11 +0800 CST
  • Martin Hope
    sleeptightAnsiC `(表达式,左值) = 右值` 在 C 或 C++ 中是有效的赋值吗?为什么有些编译器会接受/拒绝它? 2024-11-09 07:18:53 +0800 CST
  • Martin Hope
    The Mad Gamer 何时应使用 std::inplace_vector 而不是 std::vector? 2024-10-29 23:01:00 +0800 CST
  • Martin Hope
    Chad Feller 在 5.2 版中,bash 条件语句中的 [[ .. ]] 中的分号现在是可选的吗? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench 为什么双破折号 (--) 会导致此 MariaDB 子句评估为 true? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng 为什么 `dict(id=1, **{'id': 2})` 有时会引发 `KeyError: 'id'` 而不是 TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String” 2024-03-20 03:12:31 +0800 CST
  • Martin Hope
    MarkB 为什么 GCC 生成有条件执行 SIMD 实现的代码? 2024-02-17 06:17:14 +0800 CST

热门标签

python javascript c++ c# java typescript sql reactjs html

Explore

  • 主页
  • 问题
    • 最新
    • 热门
  • 标签
  • 帮助

Footer

AskOverflow.Dev

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve