围绕另一个 CGPoint 旋转一个 CGPoint

Rotating a CGPoint around another CGPoint

好的,我想将 CGPoint(A) 围绕 CGPoint(B) 旋转 50 度,有什么好的方法吗?

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

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

这是我想要做的:

这真是一道数学题。在 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 的扩展的完美案例,但为了清楚起见,我把它写得很冗长。

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)