如何从Java代码中找到实际显示密度(DPI)? [英] How to find real display density (DPI) from Java code?
问题描述
我将做一些底层渲染工作,但是我需要知道真正的显示DPI,才能制作出所有正确大小的东西.
I'm going to do some low-level rendering stuff, but I need to know real display DPI for making everything of correct size.
我找到了一种方法来做到这一点:
java.awt.Toolkit.getDefaultToolkit().getScreenResolution()
—但是在OS X上显示视网膜"的返回错误结果,它是实际DPI的1/2. (在我的情况下,应该是220,但应该是110)
I've found one way to do this:
java.awt.Toolkit.getDefaultToolkit().getScreenResolution()
— but it returns incorrect result on OS X with "retina" display, it's 1/2 of the real DPI. (In my case it should be 220, but it's 110)
因此必须有其他一些更正确的API,或者我需要仅针对OS X实现一种破解-以某种方式查找当前显示是否为视网膜".但是我也找不到任何查询此信息的方法.有此答案,但在我的计算机上Toolkit.getDefaultToolkit().getDesktopProperty("apple.awt.contentScaleFactor")
只是返回null.
So either some other, more correct API must be available, or alternatively I need to implement a hack just for OS X — somehow find if the current display is "retina". But I couldn't find any way to query for this information too. There's this answer but on my machine Toolkit.getDefaultToolkit().getDesktopProperty("apple.awt.contentScaleFactor")
just returns null.
我该怎么办?
推荐答案
看起来目前可以从java.awt.GraphicsEnvironment
获取它.这是在最新的JDK(8u112)上运行的已注释代码示例.
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;
}
这篇关于如何从Java代码中找到实际显示密度(DPI)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!