4

当我开始用一个标尺 PhoneGap 开发一个简单的应用程序时,我遇到了一个问题。我的大部分移动背景都是原生 Android,所以我从它开始。我是 javascript 和 html5 的初学者,一般来说是 web 开发。

在这里,您可以看到我与该问题相关的第一个问题。

这是我第一次尝试计算一毫米内有多少像素。这在 Android 本机代码中运行良好。

    public float getYdpi() {
        return displayMetrics.ydpi;
    }
function getPixelsPerMillimeter(){
    return YDpi/25.4f;        
}

但是毫米标记画错了。最后经过一番尝试后,我按照以下方式替换了该方法

 function getPixelsPerMillimeter(){
    var pixelsPerMms = window.innerHeight/heightInMms;
    return pixelsPerMms;    
}

HeightInMms 是用原生 android 代码计算的,简单的数学高度(以像素为单位)除以每英寸的密度像素,乘以 25.4,即一英寸有多少毫米。

public float getPhoneHeightInMillimeters(){     
    metrics = gap.getResources().getDisplayMetrics();                   
    return (metrics.heightPixels     / metrics.ydpi)*25.4f;

长话短说,我从本机代码或使用 window.outerHeight 获得的 dpi(或每英寸像素,这是我的最终目标)与我从 window.innerHeight 获得的不同。为什么?

给出真实值,我在一个高度为 800 像素的 Galaxy s2 设备上进行测试。window.outerHeight 返回 800,作为 metrics.heightPixels,但 window.innerHeight 给我 533。为什么?

4

1 回答 1

0

您可以创建一个 1 英寸宽的元素,然后询问该元素的 clientWidth(它以像素为单位)

例子:

function getPixelsPerInch() {
  var d = document.createElement("div");
  var ret;
  d.style.opacity = 0;
  d.style.width = "1in";
  d.style.position = "fixed";
  d.style.padding = 0;
  document.body.appendChild(d);
  ret = d.clientWidth;
  document.body.removeChild(d);
  return ret; 
}
alert(getPixelsPerInch());

我建议尽可能避免进行单位计算并在浏览器上中继,例如,您可以通过这种方式计算每毫米像素:

function getPixelsPerMillimeter() {
  var d = document.createElement("div");
  var ret;
  d.style.opacity = 0;
  d.style.width = "1mm";
  d.style.position = "fixed";
  d.style.padding = 0;
  document.body.appendChild(d);
  ret = d.clientWidth;
  document.body.removeChild(d);
  return ret; 
}
alert(getPixelsPerMillimeter());

或者更通用的方法:

function getPixelsPer(unit) {
  var d = document.createElement("div");
  var ret;
  d.style.opacity = 0;
  d.style.width = unit;
  d.style.position = "fixed";
  d.style.padding = 0;
  document.body.appendChild(d);
  ret = d.clientWidth;
  document.body.removeChild(d);
  return ret; 
}
function getPixelsPerInch() {
  return getPixelsPer("1in");
}
function getPixelsPerMillimeter() {
  return getPixelsPer("1mm");
}
alert(getPixelsPerInch());
alert(getPixelsPerMillimeter());
alert(getPixelsPer("1cm")); // and so on...
于 2014-09-08T20:35:56.010 回答