Interpolation.swift 1.0 KB

123456789101112131415161718192021222324252627282930313233
  1. import CoreGraphics
  2. func pointInLine(_ a: CGPoint, _ b: CGPoint, _ t: CGFloat) -> CGPoint {
  3. var c: CGPoint = .zero
  4. c.x = a.x - ((a.x - b.x) * t)
  5. c.y = a.y - ((a.y - b.y) * t)
  6. return c
  7. }
  8. func pointInQuadCurve(_ p0: CGPoint, _ p1: CGPoint, _ p2: CGPoint, _ t: CGFloat) -> CGPoint {
  9. let a = pointInLine(p0, p1, t)
  10. let b = pointInLine(p1, p2, t)
  11. return pointInLine(a, b, t)
  12. }
  13. func pointInCubicCurve(_ p0: CGPoint, _ p1: CGPoint, _ p2: CGPoint, _ p3: CGPoint, _ t: CGFloat) -> CGPoint {
  14. let a = pointInQuadCurve(p0, p1, p2, t)
  15. let b = pointInQuadCurve(p1, p2, p3, t)
  16. return pointInLine(a, b, t)
  17. }
  18. extension BinaryFloatingPoint {
  19. func inCubicCurve(_ p1: CGPoint, _ p2: CGPoint) -> Self {
  20. Self(pointInCubicCurve(.zero, p1, p2, CGPoint(x: 2, y: 1), CGFloat(self)).y)
  21. }
  22. func clamped(_ range: ClosedRange<Self> = 0 ... 1) -> Self {
  23. guard self < range.upperBound else { return range.upperBound }
  24. guard self > range.lowerBound else { return range.lowerBound }
  25. return self
  26. }
  27. }