Skip to content

Instantly share code, notes, and snippets.

View ProMode7's full-sized avatar
👨‍💻
Focusing on the future

Pramod Patel ProMode7

👨‍💻
Focusing on the future
  • Matellio Inc
  • India
  • 16:26 (UTC +05:30)
  • X @play_err_
View GitHub Profile
@ProMode7
ProMode7 / convertPxToDp.kt
Created October 23, 2020 09:41
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 int value to represent dp equivalent to px value
*/
fun convertPxToDp(context: Context, px: Float): Int {
val resources = context.resources
val metrics = resources.displayMetrics
val dp =
px / (metrics.densityDpi.toFloat() / DisplayMetrics.DENSITY_DEFAULT)
@ProMode7
ProMode7 / convertDpToPx.kt
Created October 23, 2020 09:36
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 int value to represent px equivalent to dp depending on device density
*/
fun convertDpToPx(context: Context?, dp: Float): Int {
if (context == null)
return 0
val resources = context.resources
val metrics = resources.displayMetrics