swift - 围绕另一个 CGPoint 旋转一个 CGPoint

标签 swift math rotation cgpoint degrees

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

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

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

这是我想做的:

Illustration

最佳答案

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

关于swift - 围绕另一个 CGPoint 旋转一个 CGPoint,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35683376/

相关文章:

html5 - 获取相对坐标中的设备方向旋转

c++ - 跨产品混淆

javascript - 挂钟上时针每秒旋转的 Angular 是多少?

ios - 在 Swift 中以随机间隔定期调用函数

c++ - 找到第 N 个最小的整数

java - Java 中的质因数分解程序

c++ - C++ 和 OpenGL 矩阵顺序之间的混淆(行优先 vs 列优先)

ios - UITableView 显示循环的最后一个值

ios - 如何停止 NSTimer.scheduledTimerWithTimeInterval

swift - 更新 Firebase 中的集合会返回错误 "found nil while unwrapping optional value"?