问题
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.
回答1:
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;
回答2:
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);
}
回答3:
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.
回答4:
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.
回答5:
float mm = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, 1,
getResources().getDisplayMetrics());
applyDimesion parameters
来源:https://stackoverflow.com/questions/14569963/converting-pixel-values-to-mm-android