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

如何通过触摸移动UIView,使其保持在圆圈内?,uiview,swift,core-animation,Uiview,Swift,Core Animation,我想在圆内移动UIView。UIView移动圆内的每个点,但不接触圆的边界线。我正在计算圆和视图之间的距离 var distance = sqrt( pow((touchPoint.x - selfCenter.x), 2) + pow((touchPoint.y - selfCenter.y), 2) ) 以及限制UIView向圆圈外移动 if distance <= radius { theUIView.center = touchPoint } 如果距离你的els

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

var distance = sqrt(
    pow((touchPoint.x - selfCenter.x), 2) + pow((touchPoint.y - selfCenter.y), 2)
)
以及限制UIView向圆圈外移动

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

如果距离你的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
    )
}

马丁非常感谢你们给出的答案和计算距离的捷径。干杯
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
    )
}
var distance = hypot(touchPoint.x - selfCenter.x, touchPoint.y - selfCenter.y)