我要做一些低级渲染工作,但我需要知道真实的显示 DPI 才能使所有内容都具有正确的尺寸。
我找到了一种方法来做到这一点:
java.awt.Toolkit.getDefaultToolkit().getScreenResolution()
— 但它在具有“视网膜”显示的 OS X 上返回不正确的结果,它是真实 DPI 的 1/2。 (在我的例子中应该是 220,但实际上是 110)
因此,要么必须有其他更正确的 API 可用,要么我需要为 OS X 实现一个 hack——以某种方式查找当前显示器是否为“视网膜”。但我也找不到任何方法来查询这些信息。有this answer但在我的机器上 Toolkit.getDefaultToolkit().getDesktopProperty("apple.awt.contentScaleFactor")
只是返回 null。
我该怎么做?
最佳答案
看起来目前可以从java.awt.GraphicsEnvironment
获取它。下面是带注释的代码示例,它适用于最新的 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;
}
关于java - 如何从Java代码中找到真实的显示密度(DPI)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40399643/