问题
I am developing an app for which I need the screen DPI.. I checked a few forums and got a code snippet which goes as follows:
Dimension screen = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
System.out.println("screen width: "+screen.getWidth());
System.out.println("screen height: "+screen.getHeight());
int pixelPerInch=java.awt.Toolkit.getDefaultToolkit().getScreenResolution();
System.out.println("pixelPerInch: "+pixelPerInch);
double height=screen.getHeight()/pixelPerInch;
double width=screen.getWidth()/pixelPerInch;
double x=Math.pow(height,2);
double y=Math.pow(width,2);
But whatever be the value of my screen resolution, the pixelPerInch
value remains the same at 96. What is the problem with the code??
I got another swt
code for the same thing which goes as follows:
import org.eclipse.swt.graphics.Device;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
public class MainClass {
public void run() {
Display display = new Display();
Shell shell = new Shell(display);
shell.setText("Display Device");
createContents(shell);
shell.pack();
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
display.dispose();
}
private void createContents(Shell shell) {
Device device = shell.getDisplay();
System.out.println("getBounds(): "+ device.getBounds());
System.out.println("getClientArea(): "+device.getClientArea());
System.out.println("getDepth(): "+device.getDepth());
System.out.println("getDPI(): "+device.getDPI());
device.setWarnings(true);
System.out.println("Warnings supported: "+device.getWarnings());
}
public static void main(String[] args) {
new MainClass().run();
}
But again here also whatever be my screen resolution, the getDPI()
returns the same value of 96.. What is going wrong?? Is my code wrong or am I interpreting it in a wrong way??
回答1:
The problem is no one, not even the OS, knows the exact physical dimensions of the screen. You'd need to know that in order to calculate the PPI.
There's a display setting in the control panel where the user can manually specify the PPI and by default it's set to 96.
回答2:
this code works for me on win10
import javafx.stage.Screen
double getScaleFactor() {
double trueHorizontalLines = Toolkit.getDefaultToolkit().getScreenSize().getHeight();
double scaledHorizontalLines = Screen.getPrimary().getBounds().getHeight();
double dpiScaleFactor = trueHorizontalLines / scaledHorizontalLines;
return dpiScaleFactor;
}
it uses some awt
apis though
来源:https://stackoverflow.com/questions/6544510/how-to-get-the-screen-dpi-in-java