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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
here's a fix for Swift 4;
ClosedInterval
was renamed toClosedRange
. Additionallystart
was renamed tolowerBound
whileend
was renamed toupperBound
.