围绕另一个CGPoint旋转CGPoint [英] Rotating a CGPoint around another CGPoint

查看:123
本文介绍了围绕另一个CGPoint旋转CGPoint的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Okay so I want to rotate CGPoint(A) 50 degrees around CGPoint(B) is there a good way to do that?

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

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

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

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

这就是我想要做的:

推荐答案

这确实是一个数学问题.在Swift中,您需要以下内容:

This is really a maths question. In Swift, you want something like:

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的完美案例,但是为了清楚起见,我将其保留为冗长的详细信息.

There are lots of ways to simplify this, and it's a perfect case for an extension to CGPoint, but I've left it verbose for clarity.

这篇关于围绕另一个CGPoint旋转CGPoint的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆