Rotating a CGPoint around another CGPoint
Asked Answered
D

2

5

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

Doi answered 28/2, 2016 at 13:55 Comment(0)
P
15

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.

Perseid answered 28/2, 2016 at 14:9 Comment(1)
This worked perfect! The only answer i've found that works without using CGAffineTransformOutlier
S
-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)
    }
}

Usage

var myPoint = CGPoint(x: 40, y: 50).rotate(45)
var myPoint = CGPoint(x: 40, y: 50).rotate(origin: CGPoint(x: 0, y: 0), 45)
Shakta answered 26/11, 2017 at 1:56 Comment(1)
Not sure I understand your default... by default, it will be the rather arbitrary point <0.5, 0.5> (surely <0,0> would be better?), and origin will only be nil if it is explicitly set to be nil, in which case the function will do nothing...? Some comments would help, perhaps...Perseid

© 2022 - 2024 — McMap. All rights reserved.