[Android] 在xml中“直接”使用px的小技巧和工具

原文链接:在xml中“直接”使用px的小技巧和工具

注:这个idea出自知乎某个回答,但是来源找不到了。。。工具是自己写的。

在项目开发中,UI给过来的设计图上的尺寸标识,一般以px(像素)为单位。Android工程师需根据设计图的尺寸将px换成dp,填到layout.xml中。

有了这个工具,可以很方便地实现这一点。

首先,确认设计图属于下列哪种规格:

ldpi (low) ~120dpi
mdpi (medium) ~160dpi
hdpi (high) ~240dpi
xhdpi (extra-high) ~320dpi
xxhdpi (extra-extra-high) ~480dpi
xxxhdpi (extra-extra-extra-high) ~640dpi

然后安装python,运行一个脚本:

import argparse

g_type_scale_dict = {
        "mdpi": 1,
        "hdpi": 0.67,
        "xhdpi": 0.5,
        "xxhdpi": 0.33,
        "xxxhdpi": 0.25
        }

def main(start, end, device_type):
    if device_type not in g_type_scale_dict:
        print "invaild device_type", device_type
        return

    scale = g_type_scale_dict[device_type]

    print("")
    for i in range(start, end+1):
        print('%.1fdp' % (i, i*scale))
    print("")
    for i in range(start, end+1):
        print('%.1fsp' % (i, i*scale))

if __name__ == "__main__":
    parser = argparse.ArgumentParser()

    parser.add_argument(dest="start", type=int)
    parser.add_argument(dest="end", type=int)
    parser.add_argument(dest="device_type")
    args = parser.parse_args()

    main(args.start, args.end, args.device_type)

然后在控制台中输入:

python dp_convertor.py 1 100 xxhdpi

可得到:


0.3dp
0.7dp
1.0dp
1.3dp
1.7dp
2.0dp
2.3dp
2.6dp
3.0dp
3.3dp
3.6dp
4.0dp
4.3dp
4.6dp
5.0dp
5.3dp
5.6dp
5.9dp
6.3dp
6.6dp
6.9dp
7.3dp
7.6dp
7.9dp
8.2dp
8.6dp
8.9dp
9.2dp
9.6dp
9.9dp
10.2dp
10.6dp
10.9dp
11.2dp
11.6dp
11.9dp
12.2dp
12.5dp
12.9dp
13.2dp
13.5dp
13.9dp
14.2dp
14.5dp
14.9dp
15.2dp
15.5dp
15.8dp
16.2dp
16.5dp
16.8dp
17.2dp
17.5dp
17.8dp
18.2dp
18.5dp
18.8dp
19.1dp
19.5dp
19.8dp
20.1dp
20.5dp
20.8dp
21.1dp
21.4dp
21.8dp
22.1dp
22.4dp
22.8dp
23.1dp
23.4dp
23.8dp
24.1dp
24.4dp
24.8dp
25.1dp
25.4dp
25.7dp
26.1dp
26.4dp
26.7dp
27.1dp
27.4dp
27.7dp
28.1dp
28.4dp
28.7dp
29.0dp
29.4dp
29.7dp
30.0dp
30.4dp
30.7dp
31.0dp
31.4dp
31.7dp
32.0dp
32.3dp
32.7dp
33.0dp

0.3sp
0.7sp
1.0sp
1.3sp
1.7sp
2.0sp
2.3sp
2.6sp
3.0sp
3.3sp
3.6sp
4.0sp
4.3sp
4.6sp
5.0sp
5.3sp
5.6sp
5.9sp
6.3sp
6.6sp
6.9sp
7.3sp
7.6sp
7.9sp
8.2sp
8.6sp
8.9sp
9.2sp
9.6sp
9.9sp
10.2sp
10.6sp
10.9sp
11.2sp
11.6sp
11.9sp
12.2sp
12.5sp
12.9sp
13.2sp
13.5sp
13.9sp
14.2sp
14.5sp
14.9sp
15.2sp
15.5sp
15.8sp
16.2sp
16.5sp
16.8sp
17.2sp
17.5sp
17.8sp
18.2sp
18.5sp
18.8sp
19.1sp
19.5sp
19.8sp
20.1sp
20.5sp
20.8sp
21.1sp
21.4sp
21.8sp
22.1sp
22.4sp
22.8sp
23.1sp
23.4sp
23.8sp
24.1sp
24.4sp
24.8sp
25.1sp
25.4sp
25.7sp
26.1sp
26.4sp
26.7sp
27.1sp
27.4sp
27.7sp
28.1sp
28.4sp
28.7sp
29.0sp
29.4sp
29.7sp
30.0sp
30.4sp
30.7sp
31.0sp
31.4sp
31.7sp
32.0sp
32.3sp
32.7sp
33.0sp

将以上复制到你项目的dimens.xml中,以后可以直接按照设计图的px值,在layout.xml中写@dimen/_**px了。

你可能感兴趣的:(dp,android)