Last active
July 13, 2020 20:31
-
-
Save ZevEisenberg/7ababb61eeab2e93a6d9 to your computer and use it in GitHub Desktop.
Mapping floating point numbers between two ranges in Swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import QuartzCore | |
extension CGFloat { | |
func map(from from: ClosedInterval<CGFloat>, to: ClosedInterval<CGFloat>) -> CGFloat { | |
let result = ((self - from.start) / (from.end - from.start)) * (to.end - to.start) + to.start | |
return result | |
} | |
} | |
extension Double { | |
func map(from from: ClosedInterval<CGFloat>, to: ClosedInterval<CGFloat>) -> Double { | |
return Double(CGFloat(self).map(from: from, to: to)) | |
} | |
} | |
extension Float { | |
func map(from from: ClosedInterval<CGFloat>, to: ClosedInterval<CGFloat>) -> Float { | |
return Float(CGFloat(self).map(from: from, to: to)) | |
} | |
} | |
let c = CGFloat(33.0).map(from: 0.0...100.0, to: -100...100) | |
let d = Double(27).map(from: 0...31, to: -27...18) | |
let f = Float(27).map(from: 0...21, to: -18...28) |
here's a fix for Swift 4; ClosedInterval
was renamed to ClosedRange
. Additionally start
was renamed to lowerBound
while end
was renamed to upperBound
.
import QuartzCore
extension CGFloat {
func map(from: ClosedRange<CGFloat>, to: ClosedRange<CGFloat>) -> CGFloat {
let result = ((self - from.lowerBound) / (from.upperBound - from.lowerBound)) * (to.upperBound - to.lowerBound) + to.lowerBound
return result
}
}
extension Double {
func map(from: ClosedRange<CGFloat>, to: ClosedRange<CGFloat>) -> Double {
return Double(CGFloat(self).map(from: from, to: to))
}
}
extension Float {
func map(from: ClosedRange<CGFloat>, to: ClosedRange<CGFloat>) -> Float {
return Float(CGFloat(self).map(from: from, to: to))
}
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Swift 4 giving
Use of undeclared type 'ClosedInterval'