Android开发中dp与px之间的转换

来源:互联网 发布:绿色自行车是什么软件 编辑:程序博客网 时间:2024/05/21 06:36

android开发中经常需要px和dp进行转换,特存于此方便查找使用

几种尺寸介绍

dip: device independent pixels(设备独立像素)与dp一样,只是名字不同。 不同设备有不同的显示效果,这个和设备硬件有关,一般我们为了支持WVGA、HVGA和QVGA 推荐使用这个,不依赖像素。 
px: pixels(像素). 不同设备显示效果相同。 
pt: point,是一个标准的长度单位,1pt=1/72英寸,用于印刷业,非常简单易用; 
sp: scaled pixels(放大像素),主要用于字体显示best for textsize(注意,sp设置的字体大小会跟着用户系统设置字体的大小改变而改变),如果你希望你的app界面一直显示一个样式,就用dp。

转换方法

import android.content.Context;import android.util.TypedValue;public class SizeTransfer {/** * Transfer the dip to px in float * @param context * @param dp * @return */public static float dip2pxF(Context context,float dp){return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,context.getResources().getDisplayMetrics());}/** * Transfer the dip to px in int * @param context * @param dp * @return */public static int dip2px(Context context,float dp){return (int)(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,context.getResources().getDisplayMetrics())+0.5f);}public static float px2dip(Context context,float px){final float scale = context.getResources().getDisplayMetrics().density;return px/scale;}}
     其中TypedValue中applyDimension源码在这里:
/**     * Converts an unpacked complex data value holding a dimension to its final floating      * point value. The two parameters <var>unit</var> and <var>value</var>     * are as in {@link #TYPE_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;//如果是dip转像素,则用dip乘以density        case COMPLEX_UNIT_SP:            return value * metrics.scaledDensity;//如果是sp转像素,则要乘以缩放值        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;    }
     用处:比如你想在代码中设置padding,margin或者view尺寸,如果直接用数字去设置的话,系统调用这些方法传参的默认单位是px,但有时我们希望用dp,因为dp的显示是与屏幕无关的(这里是指,当我们用dp表示长度时,在各个尺寸上显示的你看起来在屏幕所占比例差不多),这样我们就可以用工具方法将px转为dp。
这里还有篇设计文档:点击打开链接

0 0
原创粉丝点击