寻找角度b / w两点

时间:2017-02-11 21:59:30

标签: ios swift caanimation

这是我的问题,每当我点击任何按钮它应该来到中心,我使用CGAffineTransform和CABasicAnimation,但我无法得到我应该旋转的角度,每个都是一个圆形的按钮,任何帮助将不胜感激enter image description here

轮换代码

func rotateBarrel(with duration:CGFloat,angle:Double) {
    let rotationAnimaton = CABasicAnimation(keyPath: "transform.rotation.z")
    rotationAnimaton.toValue = angle

    rotationAnimaton.duration = CFTimeInterval(duration)
    barrelContainingView.layer.add(rotationAnimaton, forKey: "rotationAnimation")
    barrelContainingView.transform = CGAffineTransform(rotationAngle: CGFloat(angle))
}

角度计算代码

func angleToPoint(comparisonPoint: CGPoint) -> Double {
        let originPoint = CGPoint(x:comparisonPoint.x-initialCenterPoint.x,y:comparisonPoint.y-initialCenterPoint.y)
        return Double(atan2f(Float(originPoint.y), Float(originPoint.x)))

    }

//初始中心点是旋转前第3个按钮的中心

1 个答案:

答案 0 :(得分:0)

你想要功能atan2。您将deltaX和deltaY从中心点传递到第1点以获得第一个角度。然后在第二个点上重复以获得第二个角度,然后取角度差。这就是弧的角度。

我在Github上有一个名为TrochoidDemo的项目,其中包括使用相同数学运算的单指轻击手势识别器(对于手势识别器,我计算从手指起点到你的点的角度变化拖到。)

以下是相关代码:

let center = CGPoint(x: view!.bounds.midX, y: view!.bounds.midY)
let currentTouchPoint = touch.location(in:  view)
let previousTouchPoint = touch.previousLocation(in:  view)

//Calculate the angle from the center of the view to the previous touch point.
let previousAngle = atan2f(Float(previousTouchPoint.y - center.y),
                           Float(previousTouchPoint.x - center.x))
//Calculate the angle from the center of the view to the current touch point.
let currentAngle = atan2f(Float(currentTouchPoint.y - center.y),
                          Float(currentTouchPoint.x - center.x))

//Adjust the rotation by the change in angle.
rotation -= CGFloat(currentAngle - previousAngle)

它需要适应为你工作,但它应该向你展示基本的想法。