Advertisement
mpokhylets

Constraint rounding 360

Apr 30th, 2020
1,081
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 1.48 KB | None | 0 0
  1. func main() {
  2.     let (scale, n) = findMagic()
  3.  
  4.  
  5.     let device = UIDevice.current
  6.     let env = ProcessInfo.processInfo.environment
  7.     let model = env["SIMULATOR_MODEL_IDENTIFIER"] ?? {
  8.         var systemInfo = utsname()
  9.         uname(&systemInfo)
  10.         return withUnsafePointer(to: &systemInfo.machine) {
  11.             String(cString: UnsafeRawPointer($0).assumingMemoryBound(to: CChar.self))
  12.         }
  13.     }()
  14.     print(model, device.systemName, device.systemVersion, scale, "->", n)
  15. }
  16.  
  17.  
  18. func findMagic() -> (CGFloat, Int) {
  19.     let view = UIView()
  20.     view.translatesAutoresizingMaskIntoConstraints = false
  21.  
  22.     let w = view.widthAnchor.constraint(equalToConstant: 0)
  23.     w.isActive = true
  24.  
  25.     let scale = UIScreen.main.scale
  26.     var lo: CGFloat = 6.4 / scale
  27.     var hi: CGFloat = 6.6 / scale
  28.     while true {
  29.         let mid = (lo + hi) / 2
  30.         if mid == lo || mid == hi {
  31.             let n = findScale(lo, hi)
  32.             return (scale, n)
  33.         }
  34.         w.constant = mid
  35.  
  36.         let size = view.systemLayoutSizeFitting(
  37.             UIView.layoutFittingCompressedSize,
  38.             withHorizontalFittingPriority: .fittingSizeLevel,
  39.             verticalFittingPriority: .fittingSizeLevel
  40.         )
  41.  
  42.         if size.width < 6.5 / scale {
  43.             lo = mid
  44.         } else {
  45.             hi = mid
  46.         }
  47.     }
  48. }
  49.  
  50. func findScale(_ lo: CGFloat, _ hi: CGFloat) -> Int {
  51.     var n = 1
  52.     while round(lo * CGFloat(n)) == round(hi * CGFloat(n)) {
  53.         n += 1
  54.     }
  55.     return n
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement