Skip to content

Instantly share code, notes, and snippets.

@RayPS
Last active August 22, 2019 13:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RayPS/9ffe2dd2a85a6c13333c1161dba29149 to your computer and use it in GitHub Desktop.
Save RayPS/9ffe2dd2a85a6c13333c1161dba29149 to your computer and use it in GitHub Desktop.
Swift modulate CGFloat between two ranges.
extension CGFloat {
func modulate(from: [CGFloat], to: [CGFloat], limit: Bool) -> CGFloat {
let result = to[0] + (((self - from[0]) / (from[1] - from[0])) * (to[1] - to[0]))
return limit ? [[result, to.min()!].max()!, to.max()!].min()! : result
}
}
@RayPS
Copy link
Author

RayPS commented Jul 16, 2018

Example:

CGFloat(5.0).modulate(from: [0, 10], to: [0, 100], limit: true)       // 50
CGFloat(20.0).modulate(from: [0, 10], to: [0, 100], limit: true)      // 100
CGFloat(15.0).modulate(from: [10, 20], to: [20, 40], limit: true)     // 30
CGFloat(75.0).modulate(from: [100, 50], to: [200, 100], limit: true)  // 150
CGFloat(200.0).modulate(from: [100, 0], to: [200, 100], limit: false) // 300

@RayPS
Copy link
Author

RayPS commented Aug 22, 2019

JavaScript:

const modulate = (value, from, to, limit = false) => {
  const result = to[0] + (((value - from[0]) / (from[1] - from[0])) * (to[1] - to[0]))
  return limit ? Math.min(Math.max(result, Math.min(...to)), Math.max(...to)) : result
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment