【问题标题】:How can I move UIView with touch keeping it inside of a circle?如何通过触摸将 UIView 移动到一个圆圈内?
【发布时间】:2014-10-14 19:44:47
【问题描述】:

我想在一个圆圈内移动一个 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- 但没有帮助。

【问题讨论】:

    标签: uiview swift core-animation


    【解决方案1】:

    你的 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)
    

    【讨论】:

    • Martin 非常感谢您提供计算距离的答案和捷径。干杯。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-12
    • 1970-01-01
    • 2019-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多