Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save JoeFerrucci/31f76ad0c22d1b43bcd968f2dcd46780 to your computer and use it in GitHub Desktop.
Save JoeFerrucci/31f76ad0c22d1b43bcd968f2dcd46780 to your computer and use it in GitHub Desktop.
map a range of values to a different range of values.
private func mapValueToRange(value: CGFloat, largerRangeMin: CGFloat, largerRangeMax: CGFloat, targetRangeMin: CGFloat, targetRangeMax: CGFloat) -> CGFloat {
let largerSpan = largerRangeMax - largerRangeMin
let targetSpan = targetRangeMax - targetRangeMin
// Scaled to 0-1 range.
var scaleBy = (value - largerRangeMin) / largerSpan
if scaleBy < 0 { scaleBy = 0 }
if scaleBy > 1 { scaleBy = 1 }
let mappedValue = targetRangeMin + (scaleBy * targetSpan)
return mappedValue
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment