Android中的sp和dp的区别
16lz
2022-06-25
Android里面的sp和dp网上有很多文章都谈过了,但是看后总有一种意犹未尽的感觉。现在我也来谈谈dp和sp,和大家交流一下,不对之处欢迎拍砖。
一、dp(或者dip device independent pixels)
一种基于屏幕密度的抽象单位。在每英寸160点的显示器上,1dp=1px。不同设备有不同的显示效果,这个和设备硬件有关。
android里的代码如下:
[java] view plain copy
- "font-size: 14px; color: rgb(51, 51, 51);">// 文件位置:android4.0\frameworks\base\core\java\android\util\DisplayMetrics.java
- public static final int DENSITY_DEVICE = getDeviceDensity();
- public float density;
- public void setToDefaults() {
- 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;
- }
- private static int getDeviceDensity() {
- // 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.
- return SystemProperties.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
- public static float getDipScale(Context context) {
- final float scale = context.getResources().getDisplayMetrics().density;
- return scale;
- }
- public static int dipToPixel(float scale, int dip) {
- return (int) (dip * scale + 0.5); // dip到px的换算公式
- }
二、sp(Scaled Pixels)
主要用于字体显示,与刻度无关的一种像素,与dp类似,但是可以根据用户的字体大小首选项进行缩放。
[java] view plain copy
- "color:#333333;">// 文件位置:android4.0\packages\apps\settings\src\com\android\settings\Display.java
- private Spinner.OnItemSelectedListener mFontSizeChanged
- = new Spinner.OnItemSelectedListener() {
- public void onItemSelected(android.widget.AdapterView av, View v,
- int position, long id) {
- if (position == 0) { // 下面是设置字体比例的代码
- mCurConfig.fontScale = .75f;
- } else if (position == 2) {
- mCurConfig.fontScale = 1.25f;
- } else {
- mCurConfig.fontScale = 1.0f;
- }
- updateFontScale();
- }
- public void onNothingSelected(android.widget.AdapterView av) {
- }
- };
- private void updateFontScale() {
- mDisplayMetrics.scaledDensity = mDisplayMetrics.density *
- mCurConfig.fontScale; // 将设置的字体比例代码合到scaledDensity里去
- float size = mTextSizeTyped.getDimension(mDisplayMetrics);
- mPreview.setTextSize(TypedValue.COMPLEX_UNIT_PX, size);
- }
更多相关文章
- layout_gravity和gravity的区别
- Android中WebView和JavaScript进行简单通信
- Android系统源代码情景分析 第3版
- Flutter Android(安卓)端热修复(热更新)实践
- Android(安卓)JNI 使用的数据结构JNINativeMethod详解 ||建立And
- Android(安卓)RenderScript 的使用基础篇
- 在Ubuntu上下载、编译和安装Android最新源代码
- android中共享全局数据的方法
- Android(安卓)5.1 - 7.1 系统(framework)定制、修改、移植、总结