2

I have been trying to find an example of using the 2D transform matrix to rotate a CGPoint around the center of another CGPoint but I've had no luck finding anything recent.

Has anyone managed to achieve this? Using CGAffineTransform isn't an option in this use case as I need the points.

Thanks in advance

bevbomb
  • 689
  • 2
  • 12
  • 26

2 Answers2

3

Using CGAffineTransform wasn't really an option in my use case but i was able to successfully rotate a series of CGPoints using the method from this answer https://stackoverflow.com/a/35683523/3591202. Below is the extension i used to rotate the CGPoints.

func rotate(around center: CGPoint, with degrees: CGFloat) -> CGPoint {
    let dx = self.x - center.x
    let dy = self.y - center.y
    let radius = sqrt(dx * dx + dy * dy)
    let azimuth = atan2(dy, dx) // in radians
    let newAzimuth = azimuth + degrees * CGFloat(M_PI / 180.0) // convert it to radians
    let x = center.x + radius * cos(newAzimuth)
    let y = center.y + radius * sin(newAzimuth)
    return CGPoint(x: x, y: y)
}
Community
  • 1
  • 1
bevbomb
  • 689
  • 2
  • 12
  • 26
2

The easiest way to rotate around an arbitrary point is to move that point to zero, rotate by the desired angle, and move back to the origin. CGAffineTransform can operate with CGPoint very well:

let transform = CGAffineTransform(translationX:-center.x y:-center.y)
                    .rotate(by:angle)
                    .translateBy(x:center.x, y:center.y)
let newPoint = point.applying(transform)
clemens
  • 16,716
  • 11
  • 50
  • 65
  • This method didn't actually work in my use case. The method from here worked perfectly though! http://stackoverflow.com/a/1595337/3591202 – bevbomb Nov 22 '16 at 22:19
  • What is really not working? Your solution is sometimes unnecessary, because you're using square roots and the inverse tangens. Note: `angle` is in radians not in degrees. – clemens Nov 23 '16 at 06:59