How to read the physical screen size of OSX?

Andy Li picture Andy Li · Sep 25, 2012 · Viewed 8.4k times · Source

I would like to know the physical screen size under Mac OSX. But NSDeviceResolution is always reporting wrong value (72), so the calculation result of resolution / dpi is wrong.

Inside "About This Mac", there is a Mac model string there, mine is "15-inch, Early 2011". So I'm wondering should there be a way (in obj-c probably), to read that string and then I can use that as the physical screen size.

Any help is appreciated.

Answer

Tommy picture Tommy · Sep 25, 2012

You can use CGDisplayScreenSize to get the physical size of a screen in millimetres. From that you can compute the DPI given that you already know the resolution.

So e.g.

NSScreen *screen = [NSScreen mainScreen];
NSDictionary *description = [screen deviceDescription];
NSSize displayPixelSize = [[description objectForKey:NSDeviceSize] sizeValue];
CGSize displayPhysicalSize = CGDisplayScreenSize(
            [[description objectForKey:@"NSScreenNumber"] unsignedIntValue]);

NSLog(@"DPI is %0.2f", 
         (displayPixelSize.width / displayPhysicalSize.width) * 25.4f); 
         // there being 25.4 mm in an inch

That @"NSScreenNumber" thing looks dodgy but is the explicit documented means of obtaining a CGDirectDisplayID from an NSScreen.