1

I'm trying to get my mind around how to specify CSS dimensions in an embedded WebView in my app for Android 4.0 and higher. On the three devices I'm testing with (Nexus 4/7/10), it appears that if I use the following viewport directive:

<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">

...then any CSS dimensions in content loaded into that webview are exactly the same as device-independent pixels. That is to say, on my Nexus 10, which is 2560 physical pixels wide, if in my webview I specify something to have a width of 1280, it will exactly fill the width of the screen.

I love the idea that I could use device-independent pixels in my CSS, but I need to ensure that I am able to calculate the precise available space in such DIPs. So I expect that if a WebView has, say, 1920 physical pixels in width, its width in CSS pixels should be:

  • On an mdpi display, 1920px.
  • On an hdpi display, 1280px.
  • On an xhdpi display, 960px.
  • On an xxhdpi display, 640px.

Is this true?

Brian Rak
  • 4,912
  • 6
  • 34
  • 44

1 Answers1

0

If you want to convert physical <-> DIP pixel then you need to use window.devicePixelRatio (or DisplayMetrics): the densities names (mdpi, hdpi, etc..) are simply brackets/categories - two devices in the same category could have a different devicePixelRatio value.

For what you're doing it might be a good idea to take a look at Pixel-Perfect UI in the WebView.

marcin.kosiba
  • 3,221
  • 14
  • 19
  • I had read that page, but I just revisited it, and I think I found confirmation for my understanding. It says, "a CSS "pixel" actually takes into account the device pixel ratio (512px * 2 = 1024px)." Also, regarding the pixel ratios, my understanding is that regardless of the actual dots per inch, every device will fall into one of the predefined buckets (1.0x, 1.5x, 2.0x, and 3.0x). All the examples they give use one of those, and the site they link to (http://screensiz.es) shows only those values. – Brian Rak Nov 27 '13 at 21:57
  • @BrianRak "every device will fall into one of the predefined buckets (1.0x, 1.5x, 2.0x, and 3.0x)": The "old" N7 has a pixel ratio of 1.33.., which is neither of the above :) – marcin.kosiba Nov 27 '13 at 23:08
  • Interesting. Actually, though, 1.33 is also a predefined bucket called "tvdpi." (http://developer.android.com/guide/topics/resources/providing-resources.html) Google says it's mainly for TVs (hence the name), but at least that still seems to support the theory that devices will always use a predefined bucket. I did some more testing on other devices and they all reported a window.devicePixelRatio that exactly corresponded to one of the predefined buckets. – Brian Rak Nov 27 '13 at 23:15