【问题标题】:Finding angle b/w two points寻找两点之间的角度
【发布时间】:2017-02-11 21:59:29
【问题描述】:

这是我的问题,每当我点击它应该居中的任何按钮时,我正在使用 CGAffineTransform 和 CABasicAnimation,但我无法获得我应该旋转的角度,它们每个都是圆形按钮,任何帮助将不胜感激

旋转代码

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

    }

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

【问题讨论】:

    标签: ios swift caanimation


    【解决方案1】:

    你想要函数 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)
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-03
      • 2016-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多