2017-08-05 131 views
1

我試圖讓UIView調用object來旋轉指向另一個UIView的中心,調用orig。我似乎無法正確計算角度。我的觸發有點生疏,所以我無法弄清楚我的數學錯誤。旋轉UIView指向另一個UIView

let y0 = object.center.y 
let y1 = orig?.center.y 
let x0 = object.center.x 
let x1 = orig?.center.x 

let angle = atan2((y1! - y0), (x1! - x0)) * 180/CGFloat.pi 
rotateTo(object: object, degrees: angle, time: deplexed[1] as! CGFloat) 

回答

0

創建一個默認的對象,並認爲這是個按鈕:

let button = UIButton() 

if button.transform == CGAffineTransform.identity { 

    UIView.animate(withDuration: 0.5, animations: { 

     button.transform = CGAffineTransform(rotationAngle: self.radians(degrees: 180)) 

    }) 

} else { 

    UIView.animate(withDuration: 0.5, animations: { 

    button.transform = CGAffineTransform.identity 

    }) 
} 

func radians(degrees: CGFloat) -> CGFloat { 

    return CGFloat(degrees * CGFloat.pi/degrees)  

} 
1

爲了使轉子角度的頂部在目標點。

let direction = CGPoint(x: targetPoint.x - rotatorView.center.x, y: targetPoint.y - rotatorView.center.y) 
var angle = atan2(direction.y, direction.x) 
rotatorView.transform = CGAffineTransform(rotationAngle: angle + .pi/2) 

如果點在右邊,則atan2返回零。

enter image description here

如果你想在ATAN2結果轉換爲度:

if angle < 0 { 
    angle += .pi * 2 
} 
let degrees = angle * 180.0/.pi 

您添加一個完整的圓,如果角度爲負。 0度指向右側。