Converting Pixel values to mm - Android

时光怂恿深爱的人放手 提交于 2019-12-03 16:49:52
Nimish Choudhary

we use TypedValue.java

float px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_MM, 1, 
                getResources().getDisplayMetrics());

  public static float applyDimension(int unit, float value,
                                       DisplayMetrics metrics)
    {
        switch (unit) {
        case COMPLEX_UNIT_PX:
            return value;
        case COMPLEX_UNIT_DIP:
            return value * metrics.density;
        case COMPLEX_UNIT_SP:
            return value * metrics.scaledDensity;
        case COMPLEX_UNIT_PT:
            return value * metrics.xdpi * (1.0f/72);
        case COMPLEX_UNIT_IN:
            return value * metrics.xdpi;
        case COMPLEX_UNIT_MM:
            return value * metrics.xdpi * (1.0f/25.4f);
        }
        return 0;
    }

So you can try

Pix = mm * metrics.xdpi * (1.0f/25.4f);

MM = pix / metrics.xdpi * 25.4f;

I'd say a more robust method (which evolves with whatever new insight is applied in the Android framework) is this:

public static float pxToMm(final float px, final Context context)
{
    final DisplayMetrics dm = context.getResources().getDisplayMetrics();
    return px / TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_MM, 1, dm);
}
trumpetlicks

Try looking with this link. You are looking for screen pixel density.

getting the screen density programmatically in android?

From here you can use inches to mm conversions (1 inch == 25.4 mm) to get your answer.

Here is another option from google: http://developer.android.com/reference/android/util/DisplayMetrics.html

You'll need to scale this number to mm so use 25.4mm = 1 inch.

float mm = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, 1, 
            getResources().getDisplayMetrics());

applyDimesion parameters

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!