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

后端 未结 2 2007
长情又很酷
长情又很酷 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: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;
    }
    

提交回复
热议问题