公式像素为DP,DP到PX的android公式、像素、DP、PX

2023-09-12 21:32:06 作者:笑看人生

我想计算的像素数量可变的密度无关的像素,反之亦然。

I am trying to calculate a variable amount of pixels to density independent pixels and vice-versa.

这个公式(PX到DP):DP =(INT)(PX /(displayMetrics.densityDpi / 160)); 并没有在小型设备上工作,因为它是除以零。

This formula (px to dp): dp = (int)(px / (displayMetrics.densityDpi / 160)); does not work on small devices because it is divided by zero.

这是我的DP到PX的公式:

This is my dp to px formula:

px = (int)(dp * (displayMetrics.densityDpi / 160));

可能有人给我一些指点?

Could someone give me some pointers?

在此先感谢。

亲切的问候, 布拉姆

推荐答案

注:目前广泛使用的解决方案上面是基于 displayMetrics.density 。但是,该文档解释说,这值是一个圆形的价值,同屏'水桶'使用。例如。在我的Nexus 10将返回2,其中真正的价值将是298dpi(真实)/ 160dpi(默认值)= 1.8625。

Note: The widely used solution above is based on displayMetrics.density. However, the docs explain that this value is a rounded value, used with the screen 'buckets'. Eg. on my Nexus 10 it returns 2, where the real value would be 298dpi (real) / 160dpi (default) = 1.8625.

根据您的要求,您可能需要确切的转换,它可以实现这样的:

Depending on your requirements, you might need the exact transformation, which can be achieved like this:

这并不意味着与Android的内部DP单元被混合,因为这是当然仍基于画面水桶。你想要一个单位,应呈现相同的实际大小在不同设备上使用该功能。

This is not meant to be mixed with Android's internal dp unit, as this is of course still based on the screen buckets. Use this where you want a unit that should render the same real size on different devices.

DP转换为像素:

public int dpToPx(int dp) {
    DisplayMetrics displayMetrics = getContext().getResources().getDisplayMetrics();
    int px = Math.round(dp * (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));       
    return px;
}

转换像素DP:

Convert pixel to dp:

public int pxToDp(int px) {
    DisplayMetrics displayMetrics = getContext().getResources().getDisplayMetrics();
    int dp = Math.round(px / (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));
    return dp;
}

请注意,有xdpi和ydpi属性,你可能要区分开来,但我无法想象一个理智的显示器,其中这些值有很大的不同。

Note that there are xdpi and ydpi properties, you might want to distinguish, but I can't imagine a sane display where these values differ greatly.