Dp Pixel on Android

Basically, I forgot how to translate this every time on Android platform.
Cause on android platform, if you setup layout in xml file, you don’t need to care about this. Just forget about that.

But if you need to use dp-pixel converter in program, now here is the swiss army knife.

 * convert dp to pixel
 * @param dp
 * @param context
 * @return pixel value
public static float convertDpToPixel(float dp, Context context){
    float px = dp * getDensity(context);
    return px;

 * convert pixel to dp
 * @param pixel
 * @param context
 * @return dp value
public static float convertPixelToDp(float px, Context context){
    float dp = px / getDensity(context);
    return dp;

 * get system density value
 * @param context
 * @return desity value
public static float getDensity(Context context) {
        DisplayMetrics metrics = new DisplayMetrics();
        return metrics.density;

[Android DisplayMetrics]
[Android Screen Support]
[Online computing tool]


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 )

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s