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

后端 未结 2 2002
长情又很酷
长情又很酷 2020-12-21 12:49

I\'m going to do some low-level rendering stuff, but I need to know real display DPI for making everything of correct size.

I\'ve found one way to do this: jav

相关标签:
2条回答
  • 2020-12-21 13:03

    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;
    }
    
    0 讨论(0)
  • 2020-12-21 13:22

    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;
    }
    
    0 讨论(0)
提交回复
热议问题