Created
September 29, 2012 15:17
-
-
Save johnkil/3804323 to your computer and use it in GitHub Desktop.
Convert DIP to PX and PX to DIP
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 convets dp unit to equivalent device specific value in pixels. | |
* | |
* @param dp A value in dp(Device 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 Pixels equivalent to dp according to device | |
*/ | |
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 device 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 db 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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you!