如何移动UIView并将其保持在圆圈内?

时间:2014-10-14 19:44:48

标签: 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卡在边界内,在圆圈内。这就是我尝试写其他语句的原因。

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

问题是,我如何能够将UIView保持在圆圈内并且如果触摸继续移动则继续移动。提示会很棒。

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

1 个答案:

答案 0 :(得分:1)

你的其他情况看错了。如果你想“投射”圆圈之外的一个点 到圆圈边界然后它应该是

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)
相关问题