在Android开发中,美工妹子给我的图片都是px的单位,但是这个但是这个单位在程序中并不好,不能够自动适配。所以需要我们手动转换为dp。

#关于DP,PD,SP
PPI = Pixels per inch,每英寸上的像素数,即 “像素密度”

ppi的运算方式是:
PPI = √(长度像素数² + 宽度像素数²) / 屏幕对角线英寸数

dp:Density-independent pixels,以160PPI屏幕为标准,则1dp=1px,

dp和px的换算公式 :
dp*ppi/160 = px。比如1dp x 320ppi/160 = 2px。

sp:Scale-independent pixels,它是安卓的字体单位,以160PPI屏幕为标准,当字体大小为 100%时, 1sp=1px。

sp 与 px 的换算公式:sp*ppi/160 = px

得出:

px = dp*ppi/160
dp = px / (ppi / 160)

px = sp*ppi/160
sp = px / (ppi / 160)

dp ≈ sp

#程序
所以我就需要按计算机计算咯。但是我怎么可能手动呢,于是我就写了一个C艹的可以执行文件。帮助计算。都是些垃圾代码。不敢私藏,拿出来分享,有需要改进的就随便改。(改了给我说说,一起用)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
#include<stdlib.h>
#include<iostream>
using namespace std;
void PX_PD(float b) {
while (true)
{
float a;
cout << "请输入px:";
cin >> a;
cout << "dp = " << a / b << endl;
}
}
void PD_PX(float b) {
while (true)
{
float a;
cout << "请输入pd:";
cin >> a;
cout << "dx = " << a * b << endl;
}
}
int main() {
cout << "------------------------------------------------------------------------------------------------------------" << endl;
cout << "author:sorgs.如有需要改进的地方欢迎提出QQ:1042746391" << endl << " 由于开发Android程序员,美工妹子给的图片的单位和程序单位不一致,所以产生需要转换。(所有数据基于标准)" << endl;
cout << "dp是虚拟像素,在不同的像素密度的设备上会自动适配,这里就采用标准的就OK。(sp和dp基本一样)" << endl;
cout << "在mdpi分辨率,像素密度为160,1dp=1px" << endl;
cout << "在hdpi分辨率,像素密度为240,1dp=1.5px" << endl;
cout << "在xhdpi分辨率,像素密度为320,1dp=2px" << endl;
cout << "在xxhdpi分辨率,像素密度为480,1dp=3px" << endl;
cout << "计算公式:1dp*像素密度/160 = 实际像素数" << endl;
cout << "------------------------------------------------------------------------------------------------------------" << endl;
number3:
cout << "请输入需要转化的形式:1(px->dp) 2(dp->px)" << endl;
int i;
cin >> i;
if (i == 1) {
number1:
cout << "请输入需要计算的分辨率: 1(mdpi) 2(hdpi) 3(xhdpi) 4(xxhdpi)" << endl;
int j;
cin >> j;
if (j == 1) {
PX_PD(1);
}
if (j == 2) {
PX_PD(1.5);
}
if (j == 3) {
PX_PD(2);
}
if (j == 4) {
PX_PD(3);
}
else {
cout << "貌似输入有误呢" << endl;
goto number1;
}
}if (i == 2) {
number2:
cout << "请输入需要计算的分辨率: 1(mdpi) 2(hdpi) 3(xhdpi) 4(xxhdpi)" << endl;
int j;
cin >> j;
if (j == 1) {
PX_PD(1);
}
if (j == 2) {
PX_PD(1.5);
}
if (j == 3) {
PX_PD(2);
}
if (j == 4) {
PX_PD(3);
}
else {
cout << "貌似输入有误呢" << endl;
goto number2;
}
}
else {
cout << "输入有误哦!" << endl;
goto number3;
}
}

最后放上源码地址:https://github.com/sorgs/DP_PX.git