对于一个设备,它的宽和高是固定的,smallestWidth单位是dp, 所以要计算smallestWidth,必须先知道density, 要知道density,必须先知道屏幕物理尺寸。
那么如何知道屏幕的物理尺寸呢?在DisplayMetrics中,存在两个值xdpi和ydpi,通过这2个值就可以计算屏幕物理尺寸
物理尺寸宽 = width / displayMetrics.xdpi
物理尺寸高 = height / displayMetrics.hdpi
知道物理尺寸后,就可以计算density了,因为density涵义是设备对角线上单位inch的像素点数,得知density的计算公式是:
density = sqrt(物理尺寸宽^2 + 物理尺寸高^2) / 对角线长度(inch)
有了density, 就可以轻松计算smallestWidth了。smallestWidth表示短边长度,可以推算其计算公式是
smallestWidth = Math.min(widht, height) / density
如果对上面的计算过程不清楚,参考下面这段代码,可以帮助你更好地理解
import android.content.Context;
import android.graphics.Point;
import android.os.Build;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
public class SmallWidthCalculator {
private static SmallWidthCalculator ourInstance = new SmallWidthCalculator();
public static SmallWidthCalculator getInstance() {
return ourInstance;
}
private Context mContext;
private SmallWidthCalculator() {
}
public double getSmallWidth(Context context) {
mContext = context;
DisplayMetrics dm = context.getResources().getDisplayMetrics();
int width = dm.widthPixels;
int height = dm.heightPixels;
double dpi = getDPI(width, height);
double smallWidthDPI = 0;
int smallWidth = 0;
if (width < height)
smallWidth = width;
else
smallWidth = height;
smallWidthDPI = smallWidth / (dpi / 160);
return smallWidthDPI;
}
private double getDPI(int width,
int height) {
double dpi = 0f;
double inches = getScreenSizeInInches(width, height);
dpi = Math.sqrt(Math.pow(width, 2) + Math.pow(height, 2)) / inches;
return dpi;
}
private double getScreenSizeInInches(int width, int height) {
if (mContext != null) {
DisplayMetrics dm = mContext.getResources().getDisplayMetrics();
double wi = (double) width / (double) dm.xdpi;
double hi = (double) height / (double) dm.ydpi;
double x = Math.pow(wi, 2);
double y = Math.pow(hi, 2);
return Math.sqrt(x + y);
}
return 0;
}
}