px和dip和dp

来源:互联网 发布:navicat怎么连接mysql 编辑:程序博客网 时间:2024/05/02 00:14

1 dip 和打dp 一回事


2 px   像素 = dp的单位 * 像素/英寸  

   dp是Density-independent Pixels简写


3 转换单位的方法

  

  public static int px2dip(Context context, float pxValue) {        final float scale = context.getResources().getDisplayMetrics().density;        return (int) (pxValue / scale + 0.5f);    }    public static int dip2px(Context context, float dipValue) {        final float scale = context.getResources().getDisplayMetrics().density;        return (int) (dipValue * scale + 0.5f);    }    public static int px2sp(Context context, float pxValue) {        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;        return (int) (pxValue / fontScale + 0.5f);    }    public static int sp2px(Context context, float spValue) {        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;        return (int) (spValue * fontScale + 0.5f);    }

4 在安卓代码里面,比如getMesureHeight ,getHeight 等,单位默认px 

但是在xml 里面常采用dp 作为单位,所以在代码中需要将其进行转化


5 imageView 在使用的时候 src ,和background 有所不同

   src 添加的图片会保持图片原有的宽高比

  backgroud 添加的图片会去适配屏幕,进行一定的拉伸,放缩


6 这几天在做一个类似游戏的东西,需要将不同几张小图片,放在一个背景图片上面的弯弯曲曲的小路上,做法是这样的:

   a 将图片放在scrollView里面,用图片适配屏幕宽度,长度按照一个固定的比例来拉伸

 

AbsoluteLayout.LayoutParams params0 = new AbsoluteLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, (int)((float)screenWidth*(float)heigtWidthRatio),0,0) ;skiiBgImageView.setLayoutParams(params0) ;


   b 在代码中,用以320为宽度的屏幕设置的坐标,乘上实际屏幕宽度/320 的倍数,高度也是一个道理,将坐标写死在代码里面 

AbsoluteLayout.LayoutParams params1 = new AbsoluteLayout.LayoutParams(imageWidthInPx,imageWidthInPx,     (int)(131*widthTimes),(int)(103*heightTimes)) ; steathImageView.setLayoutParams(params1) ;

AbsoluteLayout.LayoutParams params1 = new AbsoluteLayout.LayoutParams(imageWidthInPx,imageWidthInPx,
    (int)(131*widthTimes),(int)(103*heightTimes)) ;
steathImageView.setLayoutParams(params1) ;



0 0
原创粉丝点击