How to find real display density (DPI) from Java code?

I'm going to make some materials for low-level rendering, but I need to know the actual DPI display to create the right size.

I found one way to do this: java.awt.Toolkit.getDefaultToolkit().getScreenResolution() - but it returns an incorrect result on OS X with a retina display, it is 1/2 of the actual DPI. (In my case, it should be 220, but it's 110)

Thus, any other, more correct API should be accessible, or, alternatively, I need to implement a hack only for OS X - somehow find if the current display is "retina". But I could not find a way to request this information. There is this answer , but on my machine Toolkit.getDefaultToolkit().getDesktopProperty("apple.awt.contentScaleFactor") just returns null.

How can i do this?

+2
java dpi retina-display macos
source share
1 answer

It looks like you can currently get it from java.awt.GraphicsEnvironment . Here's a commented code example that runs on the latest JDK (8u112).

 // find the display device of interest final GraphicsDevice defaultScreenDevice = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice(); // on OS X, it would be CGraphicsDevice if (defaultScreenDevice instanceof CGraphicsDevice) { final CGraphicsDevice device = (CGraphicsDevice) defaultScreenDevice; // this is the missing correction factor, it equal to 2 on HiDPI aka Retina displays final int scaleFactor = device.getScaleFactor(); // now we can compute the real DPI of the screen final double realDPI = scaleFactor * (device.getXResolution() + device.getYResolution()) / 2; } 
+3
source share

All Articles