Skip to content

Instantly share code, notes, and snippets.

@ZevEisenberg
Last active July 13, 2020 20:31
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ZevEisenberg/7ababb61eeab2e93a6d9 to your computer and use it in GitHub Desktop.
Save ZevEisenberg/7ababb61eeab2e93a6d9 to your computer and use it in GitHub Desktop.
Mapping floating point numbers between two ranges in Swift
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)
@arronhunt
Copy link

Swift 4 giving Use of undeclared type 'ClosedInterval'

@SeanROlszewski
Copy link

SeanROlszewski commented Sep 3, 2018

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