当我开始使用PhoneGap(一个标尺)开发一个简单的应用程序时,我遇到了问题。我的大多数移动背景都是原生Android,所以我从那开始。我是javascript和html5,一般网页开发的初学者。
Here您可以看到与此问题相关的第一个问题。
这是我第一次尝试计算一毫米的像素数。这在Android本机代码中工作正常。
public float getYdpi() {
return displayMetrics.ydpi;
}
function getPixelsPerMillimeter(){
return YDpi/25.4f;
}
但毫米标记被绘错了。最后经过一些尝试后,我按照以下方法替换了方法
function getPixelsPerMillimeter(){
var pixelsPerMms = window.innerHeight/heightInMms;
return pixelsPerMms;
}
HeightInMms以原生安卓代码计算,简单的数学高度(以像素为单位)除以每英寸密度像素数乘以25.4,一英寸内有多少毫米。
public float getPhoneHeightInMillimeters(){
metrics = gap.getResources().getDisplayMetrics();
return (metrics.heightPixels / metrics.ydpi)*25.4f;
长话短说,dpi(或每英寸像素数,这是我的最终目标)我从本机代码获得,或者使用window.outerHeight与我从window.innerHeight得到的不同。为什么?
给出真正的价值,我正在测试一个高度为800px的星系s2设备。 window.outerHeight返回800,作为metrics.heightPixels,但是window.innerHeight给了我533.为什么?
答案 0 :(得分: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...