Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting Pixel values to mm - Android

Tags:

android

pixel

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.

like image 413
Raj Patel Avatar asked Jan 28 '13 19:01

Raj Patel


People also ask

How do you convert pixels to MM?

How many Millimeters make 1 Pixel? 1 Pixel [px] = 0.264 583 333 333 33 Millimeters [mm] - Measurement calculator that can be used to convert Pixel to Millimeters, among others.

How much is 1mm in pixels?

» Millimeter Conversions: mm↔Pixel 1 mm = 3.779528 Pixel.


2 Answers

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;

like image 195
Nimish Choudhary Avatar answered Sep 24 '22 14:09

Nimish Choudhary


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);
}
like image 41
Jelle Fresen Avatar answered Sep 21 '22 14:09

Jelle Fresen