uiview - 如何通过触摸移动 UIView 使其保持在圆圈内?

标签 uiview swift core-animation

我想将 UIView 移动到圆圈内。 UIView 移动圆内的每个点,但不接触圆的边界线。我正在计算圆和 UIView 之间的距离。

var distance = sqrt(
    pow((touchPoint.x - selfCenter.x), 2) + pow((touchPoint.y - selfCenter.y), 2)
)

并限制 UIView 向圆外移动

if distance <= radius {
    theUIView.center = touchPoint
}

问题从这里开始,如果触摸从圆圈移出,UIView 就会卡在圆圈内部的边框上。这就是为什么我尝试编写 else 语句,就我所尝试过的而言。

if distance <= radius {
    theUIView.center = touchPoint
} else {
    theUIView.center = CGPointMake(
      touchPoint.x / distance * radius,
      touchPoint.y / distance * radius
    )
}

问题是,如果触摸继续移动,我如何才能将 UIView 保持在圆圈内并继续移动。如果有提示就太好了。

这里有类似的问题 - like this - 但没有帮助。

最佳答案

你的 else 情况看起来不对。如果你想“投影”圆外的一个点 到圆边界上,那么它应该是

if distance <= radius {
    theUIView.center = touchPoint
} else {
    theUIView.center = CGPointMake(
        selfCenter.x + (touchPoint.x - selfCenter.x) / distance * radius,
        selfCenter.y + (touchPoint.y - selfCenter.y) / distance * radius
    )
}

备注:使用 hypot() function 可以更轻松地计算距离:

var distance = hypot(touchPoint.x - selfCenter.x, touchPoint.y - selfCenter.y)

关于uiview - 如何通过触摸移动 UIView 使其保持在圆圈内?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26369064/

相关文章:

ios - 如何更改 UIview 的边框颜色?

ios - UIView 和 ScrollView 之间的 UIView 过渡翻转

swift - 如何在 Swift 中添加两个泛型值?

ios - MWFeedParser RSS 阅读器无法获取图像

iphone - 如何在所有应用程序上接收重大位置更改,而不是仅在一个 View 上接收?

ios - touchesBegan 被 AppDelegate 而不是 UIView 的子类捕获

swift - 单击时如何切换按钮图像?

ios - 将 UIView 透视变换与其他 CATranform3D 相结合

ios - 核心动画 - 组中动画的单独计时

iphone - 在一个 UIViewController 中处理多个 UITableView 的最佳方法?