Convert pixel to dp or dip and dp to pixel in Android

If we need to set dimension of any view from the java file, it will use pixel as default unit. Where as in XML file we use dp or dip(density independent pixel). So 100 dp is not equal to 100 pixel.

Screenshot_20160623-151106

200dp = 525pixel in this case

Android uses density factor to provide support to different devices with different screensize. So the conversion works as explained below.

First we will check the conversion of dp to pixel. Here dp is density independent and pixel is dependent on density. So if we need to find pixel from give dp, we need to multiply it with the density of the device.

So the equation will be like this

pixel = dp * (density of the device);

Here is the function to convert dp to pixel.

public static float dpTopixel(Context c, float dp) {
  float density = c.getResources().getDisplayMetrics().density;
  float pixel = dp * density;
  return pixel;
}

Now we will convert pixel to dp. Here we need to divide the pixel with the density of the device so the result will become independent of density(dp).

So the equation will be like this

dp = pixel / (density of the device);

Here is the function to convert pixel to dp.

public static float pixelTodp(Context c, float pixel) {
  float density = c.getResources().getDisplayMetrics().density;
  float dp = pixel / density;
  return dp;
}

Now if you want to use this value as width or height in any of your view’s LayoutParams, it will ask you for Integer(int) value and above functions will return you Float(float) value. So you have to do following thing to convert it to Integer(int).

int width = (int) dpTopixel(MainActivity.this, 200);

Please comment if you find any mistake or want to give feedback.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s