2017-02-11 65 views
0

這是我的問題,每當我點擊任何按鈕它應該來中心,我使用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))) 

    } 

//初始碼l中心點是旋轉前的第3個按鈕的中心點

回答

0

您想要函數atan2。您從中心點到點1傳遞deltaX和deltaY以獲得第一個角度。然後重複第二個點以獲得第二個角度,然後獲取角度差異。這是弧的角度。

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

這將需要一個適應爲你工作,但它應該告訴你的基本理念。