Rubber banding in swift
This file contains 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
public func rubberBand(value: CGFloat, min: CGFloat, max: CGFloat, bandLength: CGFloat) -> CGFloat { | |
if value >= min && value <= max { | |
// While we're within range we don't rubber band the value. | |
return value | |
} | |
if bandLength <= 0 { | |
// The rubber band doesn't exist, return the minimum value so that we stay put. | |
return min | |
} | |
let rubberBandCoefficient: CGFloat = 0.55 | |
// Accepts values from [0...+inf and ensures that f(x) < bandLength for all values. | |
let band: (CGFloat) -> CGFloat = { value in | |
let demoninator = value * rubberBandCoefficient / bandLength + 1 | |
return bandLength * (1 - 1 / demoninator) | |
} | |
if (value > max) { | |
return band(value - max) + max; | |
} else if (value < min) { | |
return min - band(min - value); | |
} | |
return value; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment