Last active
August 29, 2015 14:04
-
-
Save brandhill/9c947a3e2881dff66bd3 to your computer and use it in GitHub Desktop.
android : Convert dp to pixel / Convert pixel to dp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* This method converts dp unit to equivalent pixels, depending on device density. | |
* | |
* @param dp A value in dp (density independent pixels) unit. Which we need to convert into pixels | |
* @param context Context to get resources and device specific display metrics | |
* @return A float value to represent px equivalent to dp depending on device density | |
*/ | |
public static float convertDpToPixel(float dp, Context context){ | |
Resources resources = context.getResources(); | |
DisplayMetrics metrics = resources.getDisplayMetrics(); | |
float px = dp * (metrics.densityDpi / 160f); | |
return px; | |
} | |
/** | |
* This method converts device specific pixels to density independent pixels. | |
* | |
* @param px A value in px (pixels) unit. Which we need to convert into db | |
* @param context Context to get resources and device specific display metrics | |
* @return A float value to represent dp equivalent to px value | |
*/ | |
public static float convertPixelsToDp(float px, Context context){ | |
Resources resources = context.getResources(); | |
DisplayMetrics metrics = resources.getDisplayMetrics(); | |
float dp = px / (metrics.densityDpi / 160f); | |
return dp; | |
} | |
//Convert dp to pixel: | |
public int dpToPx(int dp) { | |
DisplayMetrics displayMetrics = getContext().getResources().getDisplayMetrics(); | |
int px = Math.round(dp * (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT)); | |
return px; | |
} | |
//Convert pixel to dp: | |
public int pxToDp(int px) { | |
DisplayMetrics displayMetrics = getContext().getResources().getDisplayMetrics(); | |
int dp = Math.round(px / (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT)); | |
return dp; | |
} | |
// reference : http://stackoverflow.com/questions/8309354/formula-px-to-dp-dp-to-px-android |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment