Android中px、dp、dpi、density解释和计算方式

名词解释

px:设计人员的长度单位
dp:安卓开发人员的长度单位
dpi:每英寸像素数
density:屏幕里像素值浓度
screen:屏幕尺寸
high:屏幕高度
width:屏幕宽度

计算方式

dpi=√(width²+ high²)/screen(√是开平方)
density=dpi/160
px = dp*density
dp= px/density

下面是列举的:屏幕高度1920,屏幕宽度1080,屏幕尺寸5寸的设备,计算出来的各值。

public static void main(String[] args) {
    int width = 1080;
    System.out.println("width = " + width);
    int high = 1920;
    System.out.println("high = " + high);
    int screen = 5;
    System.out.println("screen = " + screen);
    double dpi = Math.sqrt( Math.pow(width, 2) + Math.pow(high, 2)) / screen;
    System.out.println("dpi = " + dpi);
    double density = dpi / 160;
    System.out.println("density = " + density);
    double dp = 1 / density;
    System.out.println("dp = " + dp);
    double px = 1 * density;
    System.out.println("px = " + px);
    double width_dp = width / density;
    System.out.println("width_dp = " + width_dp);
    double high_dp = high / density;
    System.out.println("high_dp = " + high_dp);
}
width = 1080
high = 1920
screen = 5
dpi = 440.58143401645964
density = 2.7536339626028727
dp = 0.36315647380189553
px = 2.7536339626028727
width_dp = 392.2089917060472
high_dp = 697.2604296996394

最后,大家也可以主流机型设备信息中查询设备信息。

你可能感兴趣的:(Android中px、dp、dpi、density解释和计算方式)