Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rotating a CGPoint around another CGPoint

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(B) = CGPoint(x: 50, y: 0)

Here's what I want to do:

Illustration

like image 672
Benja0906 Avatar asked Feb 28 '16 13:02

Benja0906


1 Answers

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)
}

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.

like image 86
Grimxn Avatar answered Nov 12 '22 01:11

Grimxn