CGPoint+Utils.swift 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. //
  2. // CGPoint+Utils.swift
  3. // WeScan
  4. //
  5. // Created by Boris Emorine on 2/9/18.
  6. // Copyright © 2018 WeTransfer. All rights reserved.
  7. //
  8. import Foundation
  9. extension CGPoint {
  10. /// Returns a rectangle of a given size surounding the point.
  11. ///
  12. /// - Parameters:
  13. /// - size: The size of the rectangle that should surround the points.
  14. /// - Returns: A `CGRect` instance that surrounds this instance of `CGpoint`.
  15. func surroundingSquare(withSize size: CGFloat) -> CGRect {
  16. return CGRect(x: x - size / 2.0, y: y - size / 2.0, width: size, height: size)
  17. }
  18. /// Checks wether this point is within a given distance of another point.
  19. ///
  20. /// - Parameters:
  21. /// - delta: The minimum distance to meet for this distance to return true.
  22. /// - point: The second point to compare this instance with.
  23. /// - Returns: True if the given `CGPoint` is within the given distance of this instance of `CGPoint`.
  24. func isWithin(delta: CGFloat, ofPoint point: CGPoint) -> Bool {
  25. return (abs(x - point.x) <= delta) && (abs(y - point.y) <= delta)
  26. }
  27. /// Returns the same `CGPoint` in the cartesian coordinate system.
  28. ///
  29. /// - Parameters:
  30. /// - height: The height of the bounds this points belong to, in the current coordinate system.
  31. /// - Returns: The same point in the cartesian coordinate system.
  32. func cartesian(withHeight height: CGFloat) -> CGPoint {
  33. return CGPoint(x: x, y: height - y)
  34. }
  35. /// Returns the distance between two points
  36. func distanceTo(point: CGPoint) -> CGFloat {
  37. return hypot((self.x - point.x), (self.y - point.y))
  38. }
  39. /// Returns the closest corner from the point
  40. func closestCornerFrom(quad: Quadrilateral) -> CornerPosition {
  41. var smallestDistance = distanceTo(point: quad.topLeft)
  42. var closestCorner = CornerPosition.topLeft
  43. if distanceTo(point: quad.topRight) < smallestDistance {
  44. smallestDistance = distanceTo(point: quad.topRight)
  45. closestCorner = .topRight
  46. }
  47. if distanceTo(point: quad.bottomRight) < smallestDistance {
  48. smallestDistance = distanceTo(point: quad.bottomRight)
  49. closestCorner = .bottomRight
  50. }
  51. if distanceTo(point: quad.bottomLeft) < smallestDistance {
  52. smallestDistance = distanceTo(point: quad.bottomLeft)
  53. closestCorner = .bottomLeft
  54. }
  55. return closestCorner
  56. }
  57. }