Search code examples
macoscore-graphicsappkitfoundation

How to get the physical display resolution on MacOS?


I'm looking to find the value that "About this Mac" shows (2560 x 1600 on my 13" MBP). I have tried CGDisplayBounds and NSScreen.main, both do not return those values but instead return what is used internal for rendering / measuring.

as by Kens suggestion:

let modes = CGDisplayCopyAllDisplayModes(CGMainDisplayID(), [kCGDisplayShowDuplicateLowResolutionModes: kCFBooleanTrue] as CFDictionary) as! [CGDisplayMode]

for mode in modes {
    let flags = String(format:"%02X", mode.ioFlags)
    print("\(mode.pixelWidth)x\(mode.pixelHeight) \(mode.width)x\(mode.height) 0x\(flags)")
}

Output is:

2560x1600 2560x1600 0x2000003 <- This would be the correct one
...
2880x1800 2880x1800 0x03 <- This one is the biggest 1x mode
...

So using the biggest 1x would get the wrong result. I added the ioFlags to the output. I belive this might the missing link;-)

Thank you Ken!


Solution

  • I think the best approach is to enumerate all of the display modes (including the 1x modes) and find a) one whose ioFlags includes kDisplayModeNativeFlag, or, if none has that flag, b) the biggest 1x mode's dimensions.

    You would use CGDisplayCopyAllDisplayModes() and pass a dictionary with the key kCGDisplayShowDuplicateLowResolutionModes mapped to kCFBooleanTrue as the options to get all of the modes. You can test that CGDisplayModeGetPixelWidth() is equal to CGDisplayModeGetWidth() to determine which are 1x.