Convert dp to reverse pixels on Android

0

I need to convert dp to pixeles and pixeles to dp in Android Java.

I get the width of the screen of the device, I return a value float that is in dp

public static float getWidthDeviceDP(Context context) {
    DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
    return displayMetrics.widthPixels / displayMetrics.density;
}

and I want to define the minimum size of a TextView with the method

tv.setMinWidth(<pixel>)
    
asked by Webserveis 08.07.2016 в 20:31
source

2 answers

1

Here is an example, it would be a matter of adding it to what you already have:

From dp to px

  public int dpToPx(int dp) {
        DisplayMetrics displayMetrics = getContext().getResources().getDisplayMetrics();
        int px = Math.round(dp * (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));       
        return px;
    }

From px to dp

public int pxToDp(int px) {
    DisplayMetrics displayMetrics = getContext().getResources().getDisplayMetrics();
    int dp = Math.round(px / (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));
    return dp;
}

Response obtained from here .

    
answered by 08.07.2016 / 20:37
source
1

It would be appropriate to obtain the exact values by obtaining a float value:

Pixels to Dp:

public static float pxToDp(final Context context, final float px) {
    return px / context.getResources().getDisplayMetrics().density;
}

Dp to Pixels:

public static float dpTopx(final Context context, final float dp) {
    return dp * context.getResources().getDisplayMetrics().density;
}

But if what you want is to obtain an int value, it would be like this:

Pixels to Dp:

public int pxToDp(int px) {
    DisplayMetrics displayMetrics = getContext().getResources().getDisplayMetrics();
    return Math.round(px / (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));
}

Dp to pixels:

public int dpToPx(int dp) {
        DisplayMetrics displayMetrics = getContext().getResources().getDisplayMetrics();
        return Math.round(dp * (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));
    }
    
answered by 10.07.2016 в 04:39