Last active
May 22, 2023 16:35
-
-
Save jcoester/fea22571bf9e1cdaf86d4fed77e0cfa6 to your computer and use it in GitHub Desktop.
Java: Display Screen Resolution Aspect Ratio
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Returns the aspect ratio in "X:Y" format of given width and height | |
* e.g. getAspectRatio(1024, 768) > "4:3" | |
* e.g. getAspectRatio(1920, 1080) > "16:9" | |
* e.g. getAspectRatio(3440, 1440) > "21:9" | |
* <p> | |
* This function also works for 1366, 768 which is mathematically not 16:9, but marketed as such. | |
* | |
* @param width e.g. 1920 | |
* @param height e.g. 1080 | |
* @return aspectRatio "16:9" | |
*/ | |
public String getAspectRatio(int width, int height) { | |
// Define aspect ratios and calculate their decimal conversions | |
// List from https://en.wikipedia.org/wiki/Display_aspect_ratio | |
List<String> ratios = Arrays.asList("4:3", "5:4", "3:2", "16:10", "16:9", "17:9", "21:9", "32:9", "1:1"); | |
List<Double> ratiosDecimals = new ArrayList<>(); | |
for (String ratio : ratios) { | |
int w = Integer.parseInt(ratio.split(":")[0]); | |
int h = Integer.parseInt(ratio.split(":")[1]); | |
ratiosDecimals.add((double) w / h); | |
} | |
// Calculate absolute difference between given aspect ratio and the defined aspect ratios | |
double ratioArgs = (double) width / height; | |
List<Double> ratiosDiffs = new ArrayList<>(); | |
for (Double ratioDec : ratiosDecimals) { | |
ratiosDiffs.add(Math.abs(ratioArgs - ratioDec)); | |
} | |
// Determine and return closest available aspect ratio | |
int index = ratiosDiffs.indexOf(Collections.min(ratiosDiffs)); | |
return ratios.get(index); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment