Getting the Physical Screen Dimensions/Dpi/Pixel Density in Chrome on Android

Javscript - How can I determine physical screen width and height

You could use screen.height and screen.width properties in javascript to get the height and width of the user's screen in pixels (irrespective of the browser size).

> screen.width
2048
> screen.height
1280

This works with most browsers and certainly works with Chrome, IE, Safari, Firefox, Opera.

getting the screen density programmatically in android?

You can get info on the display from the DisplayMetrics struct:

DisplayMetrics metrics = getResources().getDisplayMetrics();

Though Android doesn't use a direct pixel mapping, it uses a handful of quantized Density Independent Pixel values then scales to the actual screen size. So the metrics.densityDpi property will be one of the DENSITY_xxx constants (120, 160, 213, 240, 320, 480 or 640 dpi).

If you need the actual lcd pixel density (perhaps for an OpenGL app) you can get it from the metrics.xdpi and metrics.ydpi properties for horizontal and vertical density respectively.

If you are targeting API Levels earlier than 4. The metrics.density property is a floating point scaling factor from the reference density (160dpi). The same value now provided by metrics.densityDpi can be calculated

int densityDpi = (int)(metrics.density * 160f);

Mobile web: how to get physical pixel size?

What you want is to check the device's pixel density - measured in DPI - as @Smamatti already mentioned you control this with CSS media queries.

Here's an article on how to cope with varying DPIs and screen sizes, using those CSS media queries.

UPDATE: here's the javascript function (from the above link) that uses a trick to figure out the current device DPI:

function getPPI(){
// create an empty element
var div = document.createElement("div");
// give it an absolute size of one inch
div.style.width="1in";
// append it to the body
var body = document.getElementsByTagName("body")[0];
body.appendChild(div);
// read the computed width
var ppi = document.defaultView.getComputedStyle(div, null).getPropertyValue('width');
// remove it again
body.removeChild(div);
// and return the value
return parseFloat(ppi);
}

Hope this helps!



Related Topics



Leave a reply



Submit