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

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

提交回复
热议问题