Tool class of Android mobile phone screen px and dp mutual conversion

  • 2021-11-02 02:41:44
  • OfStack

dp (dip): device independent pixels (device independent pixels). Different devices have different display effects, which is related to the device hardware. We recommend this to support WVGA, HVGA and QVGA, which is independent of pixels. dp is also dip, which is basically similar to sp. dp or sp can be used if you set properties such as representing length, height, etc. However, if you set the font, you need to use sp. dp is independent of density, and sp is independent of density and scale. If the screen density is 160, then dp and sp and px are identical. 1dp = 1sp = 1px, but if you use px as a unit, if the screen size is the same (assuming 3.2 inches), the screen density becomes 320. Then the original width of TextView is set to 160px, which is one and a half shorter on a 3.2-inch screen with a density of 320 than on a 3.2-inch screen with a density of 160. But if it is set to 160dp or 160sp. The system will automatically set the width property value to 320px. That is 160 * 320/160. 320/160 can be called density scaling factor. That is, if dp and sp are used, the system will automatically convert according to the change of screen density.

px: pixels (pixels). Different devices display the same effect, 1 like our HVGA stands for 320x 480 pixels, this is used more.

The code is as follows:


import android.content.Context;
public class DensityUtil {
  private static float scale;
  /**
   *  According to the resolution of the mobile phone from  dp  Unit of   Turn into  px( Pixel )
   */
  public static int dip2px(Context context, float dpValue) {
    if (scale == 0) {
      scale = context.getResources().getDisplayMetrics().density;
    }
    return (int) (dpValue * scale + 0.5f);
  }
  /**
   *  According to the resolution of the mobile phone from  px( Pixel )  Unit of   Turn into  dp
   */
  public static int px2dip(Context context, float pxValue) {
    if (scale == 0) {
      scale = context.getResources().getDisplayMetrics().density;
    }
    return (int) (pxValue / scale + 0.5f);
  }
}

Summarize


Related articles: