用于px和dp相互转换
2016-05-24 09:28
309 查看
用于px和dp相互转换
import android.content.Context; public class DensityUtil { /** * 根据手机的分辨率从 dp 的单位 转成为 px(像素) */ public static int dip2px(Context context, float dpValue) { final float scale = context.getResources().getDisplayMetrics().density; return (int) (dpValue * scale + 0.5f); } /** * 根据手机的分辨率从 px(像素) 的单位 转成为 dp */ public static int px2dip(Context context, float pxValue) { final float scale = context.getResources().getDisplayMetrics().density; return (int) (pxValue / scale + 0.5f); } }
重点,对density的理解
float scale = getResources().getDisplayMetrics().density; //这个得到的不应该叫做密度,应该是密度的一个比例。不是真实的屏幕密度,而是相对于某个值的屏幕密度。 //也可以说是相对密度 /** * The logical density of the display. This is a scaling factor for the * Density Independent Pixel unit, where one DIP is one pixel on an * approximately 160 dpi screen (for example a 240x320, 1.5"x2" screen), * providing the baseline of the system's display. Thus on a 160dpi * screen this density value will be 1; on a 120 dpi screen it would be * .75; etc. * * This value does not exactly follow the real screen size (as given by * xdpi and ydpi, but rather is used to scale the size of the overall UI * in steps based on gross changes in the display dpi. For example, a * 240x320 screen will have a density of 1 even if its width is * 1.8", 1.3", etc. However, if the screen resolution is increased to * 320x480 but the screen size remained 1.5"x2" then the density would * be increased (probably to 1.5). */ /** * 显示器的逻辑密度,这是【独立的像素密度单位(首先明白dip是个单位)】的一个缩放因子, * 在屏幕密度大约为160dpi的屏幕上,一个dip等于一个px,这个提供了系统显示器的一个基线(这句我实在翻译不了)。 * 例如:屏幕为240*320的手机屏幕,其尺寸为 1.5"*2" 也就是1.5英寸乘2英寸的屏幕 * 它的dpi(屏幕像素密度,也就是每英寸的像素数,dpi是dot per inch的缩写)大约就为160dpi, * 所以在这个手机上dp和px的长度(可以说是长度,最起码从你的视觉感官上来说是这样的)是相等的。 * 因此在一个屏幕密度为160dpi的手机屏幕上density的值为1,而在120dpi的手机上为0.75等等 * (这里有一句话没翻译,实在读不通顺,不过通过下面的举例应该能看懂) * 例如:一个240*320的屏幕尽管他的屏幕尺寸为1.8"*1.3",(我算了下这个的dpi大约为180dpi多点) * 但是它的density还是1(也就是说取了近似值) * 然而,如果屏幕分辨率增加到320*480 但是屏幕尺寸仍然保持1.5"*2" 的时候(和最开始的例子比较) * 这个手机的density将会增加(可能会增加到1.5) */
转载请注明:Itroadmap » getResources().getDisplayMetrics().density 的理解(px和dp相互转换)
相关文章推荐
- Android Native 绘图方法
- C#中struct和class的区别详解
- VBS ArrayList Class vbs中的数组类
- 大家看了就明白了css样式中类class与标识id选择符的区别小结
- 深入了解PHP类Class的概念
- jquery 表单验证之通过 class验证表单不为空
- setAttribute 与 class冲突解决
- JavaScript中的类(Class)详细介绍
- javascript面向对象包装类Class封装类库剖析
- 详解js中class的多种函数封装方法
- jQuery使用hide方法隐藏指定元素class样式用法实例
- jQuery给多个不同元素添加class样式的方法
- jQuery点击改变class并toggle及toggleClass()方法定义用法
- jquery采用oop模式class类的使用示例
- jquery点击改变class并toggle的实现代码
- JavaScript更改class和id的方法
- 一篇入门的php Class 文章
- 深入C++中struct与class的区别分析
- js中设置元素class的三种方法小结
- JavaScript操作class和style样式代码详解