sp和dp很类似但唯一的区别是,Android系统允许用户自定义文字尺寸大小(小、正常、大、超大等等),当文字尺寸是“正常”时1sp=1dp=0.00625英寸,而当文字尺寸是“大”或“超大”时,1sp>1dp=0.00625英寸。类似我们在windows里调整字体尺寸以后的效果——窗口大小不变,只有文字大小改变。
dp代码(或者dipdevice independent pixels)
// 文件位置:android4.0\frameworks\base\core\java\android\util\DisplayMetrics.java
publicstaticfinalintDENSITY_DEVICE = getDeviceDensity();
publicfloatdensity;
publicvoidsetToDefaults() {
widthPixels =0;
heightPixels =0;
density = DENSITY_DEVICE / (float) DENSITY_DEFAULT;// 这里dp用的比例
densityDpi = DENSITY_DEVICE;
scaledDensity = density;// 这是sp用的比例
xdpi = DENSITY_DEVICE;
ydpi = DENSITY_DEVICE;
noncompatWidthPixels =0;
noncompatHeightPixels =0;
}
privatestaticintgetDeviceDensity() {
// qemu.sf.lcd_density can be used to override ro.sf.lcd_density
// when running in the emulator, allowing for dynamic configurations.
// The reason for this is that ro.sf.lcd_density is write-once and is
// set by the init process when it parses build.prop before anything else.
returnSystemProperties.getInt("qemu.sf.lcd_density",
SystemProperties.getInt("ro.sf.lcd_density", DENSITY_DEFAULT));// 从系统属性ro.sf.lcd_density里获取屏幕密度
// 文件位置:android4.0\packages\inputmethods\latinime\java\src\com\android\inputmethod\latin\Utils.java
publicstaticfloatgetDipScale(Context context) {
finalfloatscale = context.getResources().getDisplayMetrics().density;
returnscale;
}
publicstaticintdipToPixel(floatscale,intdip) {
return(int) (dip * scale +0.5);// dip到px的换算公式
}
sp(Scaled Pixels)代码
// 文件位置:android4.0\packages\apps\settings\src\com\android\settings\Display.java
privateSpinner.OnItemSelectedListener mFontSizeChanged
=newSpinner.OnItemSelectedListener() {
publicvoidonItemSelected(android.widget.AdapterView av, View v,
intposition,longid) {
if(position ==0) {// 下面是设置字体比例的代码
mCurConfig.fontScale = .75f;
}elseif(position ==2) {
mCurConfig.fontScale =1.25f;
}else{
mCurConfig.fontScale =1.0f;
}
updateFontScale();
}
publicvoidonNothingSelected(android.widget.AdapterView av) {
}
};
privatevoidupdateFontScale() {
mDisplayMetrics.scaledDensity = mDisplayMetrics.density *
mCurConfig.fontScale;// 将设置的字体比例代码合到scaledDensity里去
floatsize = mTextSizeTyped.getDimension(mDisplayMetrics);
mPreview.setTextSize(TypedValue.COMPLEX_UNIT_PX, size);
}