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

帅比萌擦擦* 提交于 2019-11-29 16:17:14

Looks like it's currently possible to get it from java.awt.GraphicsEnvironment. Here's commented code example which does work on 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's equal to 2 on HiDPI a.k.a. 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;
}

Here's an example adopted from @sarge-borsch that won't throw compile errors on Windows and Linux.

public static int getScaleFactor() {
    try {
        // Use reflection to avoid compile errors on non-macOS environments
        Object screen = Class.forName("sun.awt.CGraphicsDevice").cast(GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice());
        Method getScaleFactor = screen.getClass().getDeclaredMethod("getScaleFactor");
        Object obj = getScaleFactor.invoke(screen);
        if (obj instanceof Integer) {
            return ((Integer)obj).intValue();
        }
    } catch (Exception e) {
        System.out.println("Unable to determine screen scale factor.  Defaulting to 1.");
    }
    return 1;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!