gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 10:21:28 32 4
gpt4 key购买 nike

我想将 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/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com