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.
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.
» Millimeter Conversions: mm↔Pixel 1 mm = 3.779528 Pixel.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With