Created
February 16, 2020 06:54
-
-
Save ch8n/cfaa0421a0d865fa712b1221e6645797 to your computer and use it in GitHub Desktop.
Android display metrics
This file contains hidden or 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 | |
*/ | |
inline fun Context.dpToPixel(dp:Float) : Float { | |
return dp * (resource.displayMertics.densityDpi / DisplayMetrics.DENSITY_DEFAULT).toFloat(); | |
} | |
/** | |
* 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 | |
*/ | |
inline fun Context.pixelToDp(px:Float) : Float { | |
return px / (resource.displayMertics.densityDpi / DisplayMetrics.DENSITY_DEFAULT).toFloat(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment