【问题标题】:window.innerHeight vs window.outerHeight to calculate density?window.innerHeight vs window.outerHeight 计算密度?
【发布时间】:2012-09-23 00:17:30
【问题描述】:

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

Here你可以看到我与该问题相关的第一个问题。

这是我第一次尝试计算一毫米内有多少像素。这在 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 获得的不同。为什么?

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

【问题讨论】:

  • 来自 MDN,window.outerHeight 获取整个浏览器窗口的像素高度。它表示整个浏览器窗口的高度,包括侧边栏(如果展开)、窗口镶边和窗口大小调整边框/句柄。

标签: javascript android cordova


【解决方案1】:

你可以创建一个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...

【讨论】:

    猜你喜欢
    • 2015-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-27
    • 2020-04-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多