From 610728c9f16535d92a33b37bed98fcfe755bfe84 Mon Sep 17 00:00:00 2001 From: bruvzg <7645683+bruvzg@users.noreply.github.com> Date: Thu, 1 Oct 2020 22:55:54 +0300 Subject: [PATCH] [3.2] Fix `get_screen_dpi` on macOS for non fractional display scales and update documentation. --- doc/classes/OS.xml | 3 ++- platform/osx/os_osx.mm | 11 +++++++++-- 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/doc/classes/OS.xml b/doc/classes/OS.xml index 436c1eb3926..50f5707e750 100644 --- a/doc/classes/OS.xml +++ b/doc/classes/OS.xml @@ -361,7 +361,8 @@ Returns the dots per inch density of the specified screen. If [code]screen[/code] is [/code]-1[/code] (the default value), the current screen will be used. - On Android devices, the actual screen densities are grouped into six generalized densities: + [b]Note:[/b] On macOS, returned value is inaccurate if fractional display scaling mode is used. + [b]Note:[/b] On Android devices, the actual screen densities are grouped into six generalized densities: [codeblock] ldpi - 120 dpi mdpi - 160 dpi diff --git a/platform/osx/os_osx.mm b/platform/osx/os_osx.mm index be023594a1d..1f60ed59b35 100644 --- a/platform/osx/os_osx.mm +++ b/platform/osx/os_osx.mm @@ -2471,8 +2471,15 @@ int OS_OSX::get_screen_dpi(int p_screen) const { NSArray *screenArray = [NSScreen screens]; if ((NSUInteger)p_screen < [screenArray count]) { NSDictionary *description = [[screenArray objectAtIndex:p_screen] deviceDescription]; - NSSize displayDPI = [[description objectForKey:NSDeviceResolution] sizeValue]; - return (displayDPI.width + displayDPI.height) / 2; + + const NSSize displayPixelSize = [[description objectForKey:NSDeviceSize] sizeValue]; + const CGSize displayPhysicalSize = CGDisplayScreenSize([[description objectForKey:@"NSScreenNumber"] unsignedIntValue]); + float scale = [[screenArray objectAtIndex:p_screen] backingScaleFactor]; + + float den2 = (displayPhysicalSize.width / 25.4f) * (displayPhysicalSize.width / 25.4f) + (displayPhysicalSize.height / 25.4f) * (displayPhysicalSize.height / 25.4f); + if (den2 > 0.0f) { + return ceil(sqrt(displayPixelSize.width * displayPixelSize.width + displayPixelSize.height * displayPixelSize.height) / sqrt(den2) * scale); + } } return 72;