-
Notifications
You must be signed in to change notification settings - Fork 111
/
PolarPoint.swift
49 lines (39 loc) · 1.41 KB
/
PolarPoint.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
//
// PolarPoint.swift
//
// Created by Andrew Madsen on 2/26/15.
// Copyright (c) 2015 Open Reel Software. All rights reserved.
//
import Foundation
struct PolarPoint {
var radius: CGFloat
var theta: CGFloat
init(radius: Int, theta: Int) {
self.radius = CGFloat(radius)
self.theta = CGFloat(theta)
}
init<T: BinaryFloatingPoint>(radius: T, theta: T) {
self.radius = CGFloat(radius)
self.theta = CGFloat(theta)
}
init(point: CGPoint, centerPoint: CGPoint) {
let translatedPoint = CGPoint(x: point.x - centerPoint.x, y: point.y - centerPoint.y)
let xDistance = abs(point.x - centerPoint.x)
let yDistance = abs(point.y - centerPoint.y)
self.radius = (pow(xDistance, 2.0) + pow(yDistance, 2.0)).squareRoot()
self.theta = atan2(translatedPoint.y, translatedPoint.x)
}
static func degreesToRadians<T: BinaryFloatingPoint>(_ degrees: T) -> T {
return degrees * T.pi / T(180.0)
}
static func radiansToDegrees<T: BinaryFloatingPoint>(_ radians: T) -> T {
return radians * T(180.0) / T.pi
}
}
extension CGPoint {
init(polarPoint: PolarPoint, centerPoint: CGPoint) {
let x = CGFloat(polarPoint.radius * cos(polarPoint.theta)) + centerPoint.x
let y = CGFloat(polarPoint.radius * sin(polarPoint.theta)) + centerPoint.y
self.init(x: x, y: y)
}
}