Android的计量单位px/dip/dp/sp/pt/in/mm,及相互转换

px   :原始像素点(raw Pixel)。
dip  :设备独立点(Device Independent Pixel),会根据屏幕的密度(density)进行缩放。
dp   :同dip,是其简写。
sp   :缩放像素点(Scaled Pixel),会根据用户选择的字体大小(scaledDensity)进行缩放。

pt    :磅(Point),英寸的1/72。

in    :英寸(Inch)。

mm :毫米(Millimeter)。

建议:文字尺寸使用sp,其他尺寸使用dp

PPI = Pixels per inch,每英寸上的像素数,即 "像素密度"

  • xhdpi: 2.0
  • hdpi: 1.5
  • mdpi: 1.0 (baseline) 160
  • ldpi: 0.75
dp和px的换算公式 dp*ppi = px。比如xhdpi,1dp x 2ppi = 2px。
sppx的换算公式 :sp*ppi = px。

    //android.util.TypedValue

    /**  complex unit: Value is raw pixels. */
    public static final int COMPLEX_UNIT_PX = 0;
    /**  complex unit: Value is Device Independent Pixels. */
    public static final int COMPLEX_UNIT_DIP = 1;
    /**  complex unit: Value is a scaled pixel. */
    public static final int COMPLEX_UNIT_SP = 2;
    /**  complex unit: Value is in points. */
    public static final int COMPLEX_UNIT_PT = 3;
    /**  complex unit: Value is in inches. */
    public static final int COMPLEX_UNIT_IN = 4;
    /**  complex unit: Value is in millimeters. */
    public static final int COMPLEX_UNIT_MM = 5;

    /** 
     * Converts an unpacked complex data value holding a dimension to its final
     * floating point value. The two parameters unit and value are as in dimension.
     *  
     * @param unit The unit to convert from.
     * @param value The value to apply the unit to.
     * @param metrics Current display metrics to use in the conversion -- 
     *                supplies display density and scaling information.
     * 
     * @return The complex floating point value multiplied by the appropriate 
     * metrics depending on its unit. 
     */
    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;
    }
更多,请参看: http://blog.csdn.net/ithomer/article/details/6688303

你可能感兴趣的:(Android图形界面)