用于px和dp相互转换

 用于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相互转换)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值