首页 > 解决方案 > UIPanGestureRecognizer - 仅在连接 2 个点的线路径内拖动 UIView

问题描述

我有一条线 ( CAShapeLayer) 连接两点。这两个点可以在屏幕上的任何位置,并且它们的坐标是已知的。中间的点也有 aUIPanGestureRecognizer但我希望它只能在线条内拖动(所以它不能离开线条 - 线条必须随时直接穿过中间点的中心)。

我知道我可以计算点的可拖动位置

let translation = gesture.translation(in: self.view) 

并通过 X 或 Y 轴限制它,但是这里需要什么样的计算才能将它只拖到行内?

在此处输入图像描述

标签: iosswiftmathformulauigesturerecognizer

解决方案


谢谢您的回答!我设法找到了最合适的解决方案。我使用这个答案的公式: https ://stackoverflow.com/a/57383437/1088286

function getPositionAlongTheLine(x1, y1, x2, y2, percentage) {
    return {x : x1 * (1.0 - percentage) + x2 * percentage, y : y1 * (1.0 - percentage) + y2 * percentage};
}

这就是我在didMove: UIPanGestureRecogniser方法中使用的代码:

            touchPoint.center = getPositionAlongTheLine(firstPoint: mainPoint1,
                                                        secondPoint: mainPoint2,
                                                        percentage: percentage)

其中 mainPoint1 和 mainPoint2 是侧面按钮。完美运行!


推荐阅读