2017-08-05 134 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度指向右侧。