What is the difference between px, dp, dip, and sp?

Asked 2 years ago, Updated 2 years ago, 154 views

What is the difference between px dip dsp on Android?

android-layout user-interface amdroid unit

2022-09-21 21:23

2 Answers

The actual pixel entering the device's screen (one blue dot in the image). alt text The resolution of all previous devices (now generic monitors) was mdpi (160dip) so 1dp = 1px, but with Retina Disklet and higher resolutions, the size of 1px changed from the l/m/h/x dip. dpi means the number of pixels per inch. alt text

Since px alone varies in size depending on the resolution, it is a unit made to support various resolutions of Android phones. Whether it's a big screen or a small screen, it makes it look the same size with your real eyes. In other words, the length of about 1cm from the low resolution phone is supposed to look like 1cm even from the high resolution phone. Refer to px/dp calculator for conversion from px to dp.

Please refer to how to obtain dpi and how to change dp directly in java.

/* How to get dpi and density*/
DisplayMetrics outMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(outMetrics);
int dpi = outMetrics.densityDpi;
float density =  outMetrics.density;
/*How to change dp to px in java code
Dp can be converted to px using density or dpi in java code, but it can be obtained as follows using TypedValue.
*/
public int dpToPixel(int dp){
int px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, DP, context.getResources().getDisplayMetrics());
}

It is similar to dp, but in addition, it is automatically resized by the font size selected by the user. We recommend that you use this unit to specify the font size. Use Android pixel calculator if you need to change other units to sp units.

SummaryFor UI elements such as leiout, dp(dip) is recommended, and sp is recommended for letter size. Do not use px or pt.


2022-09-21 21:23

Px is a pixel Sp is a pixel independent of size Dip and dp are the same meaning, but they are pixels independent of density.

Sp is usually used in font size Dip can be used anywhere. Since dip supports multi-device environments, we recommend using dip or dp instead of pixels.


2022-09-21 21:23

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.