Android万能分辨率适应法

时间:2014-05-01 21:21:38   收藏:0   阅读:548

在Android开发中比较头疼的是Android的分辨率问题,那么这里给大家介绍个万能办法,这个办法的优点是可以实现万能适应,给开发和美工设计提供了依据,但是对开发来说代码量也不少,具体办法你听我来说:

(1)获取屏幕的尺寸

1 WindowManager windowManager = (WindowManager)
2          getSystemService(Context.WINDOW_SERVICE);
3  Display d = windowManager.getDefaultDisplay();
4  mWidth = d.getWidth();
5  mHeight = d.getHeight();
6  DisplayMetrics dm = getResources().getDisplayMetrics();
7  mScreenDensity = dm.density;

(2)美工设计图的尺寸

  uiWidth,uiHeight

(3)获取缩放比例

1 float scaleWidth = mWidth / uiWidth;
2 float scaleHeight = mHeight/ uiHeight;

(4)所有布局的尺寸用代码实现:

01 public static int getWidthSize(int size){
02     return (int) (size * scaleWidth);
03 }
04  
05 public static int getHightSize(int size){
06     return (int) (size * scaleHeight);
07 }
08  
09 public static float getTextSize(int pxSize){
10     return (pxSize*scaleHeight) / mScreenDensity;
11 }
12  
13 public static void setViewSize(int width, int height, View v){
14     int paramWidth = getWidthSize(width);
15     int paramHeight = getHightSize(height);
16     ViewGroup.MarginLayoutParams params
17            = (ViewGroup.MarginLayoutParams) v.getLayoutParams();
18     if (width != INVALID){
19         params.width = paramWidth;
20     }
21     if (height != INVALID){
22         params.height = paramHeight;
23     }
24     v.setLayoutParams(params);
25 }
26  
27 public static void setViewPadding(int left, int top, int right, int bottom,
28         View v){
29     left = getWidthSize(left);
30     top = getHightSize(top);
31     right = getWidthSize(right);
32     bottom = getWidthSize(bottom);
33     v.setPadding(left, top, right, bottom);
34 }
35  
36  
37 public static void setViewMargin(int left, int top, int right, int bottom,
38         View v){
39     int paramLeft = getWidthSize(left);
40     int paramTop =  getHightSize(top);
41     int paramRight = getWidthSize(right);
42     int paramBottom = getHightSize(bottom);
43     ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams)
44                  v.getLayoutParams();
45     if (left != INVALID){
46         params.leftMargin = paramLeft;
47     }
48     if (right != INVALID){
49         params.rightMargin = paramRight;
50     }
51     if (top != INVALID){
52         params.topMargin = paramTop;
53     }
54     if (bottom != INVALID){
55         params.bottomMargin = paramBottom;
56     }
57     v.setLayoutParams(params);
58 }

    (5)这里是设置尺寸的代码:

1 setViewSize(100100, mView);
2 setViewMargin(200020, mView);
3 setViewPadding(10101010, mView);
4 mTextView.setTextSize(getTextSize(30));

    由上在设计效果图时,可对图内元素进行尺寸标注,程序即可实现按比例缩放。

 

 

Android万能分辨率适应法,码迷,mamicode.com

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!