Skip to content

Instantly share code, notes, and snippets.

@jverkoey
Created November 30, 2016 06:55
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jverkoey/3955471c6670386c54e1d62d9c965b53 to your computer and use it in GitHub Desktop.
Save jverkoey/3955471c6670386c54e1d62d9c965b53 to your computer and use it in GitHub Desktop.
Rubber banding in swift
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