Because of the open source of Android, so the current market above the resolution of the Android phone is particularly much, so that I have to adapt to a certain degree of difficulty. To do well, we should first understand the concepts of resolution, PPI, screen size, and the conversion relationship between units at different screen densities.
Screen size refers to the length of the diagonal of the screen, usually measured in "inch".
Resolution refers to the number of pixels on the phone screen, such as 720x1280, which means that the screen has a width of 720 pixels and a height of 1280 pixels.
DPI pixels per inch, which is obtained by dividing the diagonal pixel points by the size of the screen. So the density of the screen corresponds to:, because of the different screen density, resulting in the same size of the pixel length, on different densities of the screen display length is different.
The Android system uses MDPI, a screen with a density value of 160, as the standard, 1PX=1DP on this screen. Other screens can be converted by scale, 1dp=1px in mdpi, 1dp=1.5px in hdpi, xhdpi in 1dp=2px, xxxhdpi in 1dp=3px. Thus we can get the direct conversion ratio of each resolution, ldpi:mdpi:hdpi:xhdpi:xxhdpi=3:4:6:8:12.
The conversion code between the units is provided below:
public class displayutil{public static int Px2dip (Context context,float pxvalue) { final float scale= Context.getresources (). Getdisplaymetrics (). density; return (int) (pxvalue/scale+0.5f); } public static int dip2px (Context context,float dipvalue) { final float scale=context.getresources (). Getdisplaymetrics (). density; return (int) (Dipvalue * scale +0.5f); } public static int px2sp (Context context,float pxvalue) { final float scale=context.getresources (). Getdisplaymetrics (). density; return (int) (Pxvalue/fontscale +0.5f); } public static int sp2px (Context context,float pxvalue) { final float scale=context.getresources (). Getdisplaymetrics (). density; return (int) (Pxvalue*fontscale +0.5f);} }
Where density is the conversion scale mentioned earlier, and the system also provides the Typedvalue class to help us convert, the code example is as follows:
protected int dp2px (int dp) { return (int) typedvalue.applydimension (typedvalue.complex_unit_dip,dp,getresources (). Getdisplaymetrics ());} protected int sp2px (int sp) { return (int) typedvalue.applydimension (typedvalue.complex_unit_sp,sp,getresources ( ). Getdisplaymetrics ());}
Screen density and unit conversions for the Android development series