围绕另一个CGPoint旋转CGPoint

时间:2016-02-28 13:55:04

标签: swift math rotation cgpoint degrees

好的,所以我想在CGPoint周围旋转CGPoint(A)50度(B)有一个很好的方法吗?

CGPoint(A)= CGPoint(x: 50, y: 100)

CGPoint(B)= CGPoint(x: 50, y: 0)

这就是我想要做的事情:

Illustration

2 个答案:

答案 0 :(得分:9)

这确实是一个数学问题。在Swift中,你需要类似的东西:

func rotatePoint(target: CGPoint, aroundOrigin origin: CGPoint, byDegrees: CGFloat) -> CGPoint {
    let dx = target.x - origin.x
    let dy = target.y - origin.y
    let radius = sqrt(dx * dx + dy * dy)
    let azimuth = atan2(dy, dx) // in radians
    let newAzimuth = azimuth + byDegrees * CGFloat(M_PI / 180.0) // convert it to radians
    let x = origin.x + radius * cos(newAzimuth)
    let y = origin.y + radius * sin(newAzimuth)
    return CGPoint(x: x, y: y)
}

有很多方法可以简化这一点,它是CGPoint扩展的完美案例,但为了清晰起见,我已经将其详细说明了。

答案 1 :(得分:-1)

public extension CGFloat {
    ///Returns radians if given degrees
    var radians: CGFloat{return self * .pi / 180}
}    

public extension CGPoint {
    ///Rotates point by given degrees
    func rotate(origin: CGPoint? = CGPoint(x: 0.5, y: 0.5), _ byDegrees: CGFloat) -> CGPoint {
        guard let origin = origin else {return self}

        let rotationSin = sin(byDegrees.radians)
        let rotationCos = cos(byDegrees.radians)

        let x = (self.x * rotationCos - self.y * rotationSin) + origin.x
        let y = (self.x * rotationSin + self.y * rotationCos) + origin.y

        return CGPoint(x: x, y: y)
    }
}

<强>用法

var myPoint = CGPoint(x: 40, y: 50).rotate(45)
var myPoint = CGPoint(x: 40, y: 50).rotate(origin: CGPoint(x: 0, y: 0), 45)