8

Because of specific needs, in my android layout, I have used "mm" to provide size. In TextView also, I have provided sizes in "mm". When I do textView.getTextSize(), the size returned is always in pixel values. I want to convert that pixel value in "mm". For example, if I have set font size as "2mm", then on any device, when I do getTextSize(), I would like to get "2mm".

Should I use any specific method for that? I could find answers to convert "mm" to "pixel" but could not find anything about converting vice-versa.

Andreas
  • 5,393
  • 9
  • 44
  • 53
Raj Patel
  • 83
  • 1
  • 1
  • 4

5 Answers5

11

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;

Oliv
  • 10,221
  • 3
  • 55
  • 76
Nimish Choudhary
  • 2,048
  • 18
  • 17
8

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);
}
Jelle Fresen
  • 1,916
  • 1
  • 20
  • 24
0

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.

Community
  • 1
  • 1
trumpetlicks
  • 7,033
  • 2
  • 19
  • 33
0

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.

paulczak
  • 96
  • 6
-2
float mm = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, 1, 
            getResources().getDisplayMetrics());

applyDimesion parameters

Vikalp Patel
  • 10,669
  • 6
  • 61
  • 96