Skip to content

Commit

Permalink
✨ Ability to get screen size in inches
Browse files Browse the repository at this point in the history
  • Loading branch information
MrKai77 committed Jul 9, 2024
1 parent a11e270 commit 3c7a9c8
Showing 1 changed file with 38 additions and 0 deletions.
38 changes: 38 additions & 0 deletions Loop/Extensions/NSScreen+Extensions.swift
Original file line number Diff line number Diff line change
Expand Up @@ -77,3 +77,41 @@ extension NSScreen {
frame.maxY - visibleFrame.maxY
}
}

// MARK: - Calculate physical screen size

extension NSScreen {
// Returns diagonal size in inches
var diagonalSize: CGFloat {
let unitsPerInch = unitsPerInch
let screenSizeInInches = CGSize(
width: frame.width / unitsPerInch.width,
height: frame.height / unitsPerInch.height
)

// Just the pythagorean theorem
let diagonalSize = sqrt(pow(screenSizeInInches.width, 2) + pow(screenSizeInInches.height, 2))

return diagonalSize
}

private var unitsPerInch: CGSize {
// We need to convert from mm to inch because CGDisplayScreenSize returns units in mm.
let millimetersPerInch: CGFloat = 25.4

let screenDescription = deviceDescription
if let displayUnitSize = (screenDescription[NSDeviceDescriptionKey.size] as? NSValue)?.sizeValue,
let screenNumber = (screenDescription[NSDeviceDescriptionKey("NSScreenNumber")] as? NSNumber)?.uint32Value {
let displayPhysicalSize = CGDisplayScreenSize(screenNumber)

return CGSize(
width: millimetersPerInch * displayUnitSize.width / displayPhysicalSize.width,
height: millimetersPerInch * displayUnitSize.height / displayPhysicalSize.height
)
} else {
// this is the same as what CoreGraphics assumes if no EDID data is available from the display device
// https://developer.apple.com/documentation/coregraphics/1456599-cgdisplayscreensize?language=objc
return CGSize(width: 72.0, height: 72.0)
}
}
}

0 comments on commit 3c7a9c8

Please sign in to comment.