Skip to content

Instantly share code, notes, and snippets.

@saeedsh92
Forked from kevinhaitsma/MetricsUtil.kt
Created September 23, 2019 12:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save saeedsh92/1fccf4c28ac96c4180465f9cda5b69d1 to your computer and use it in GitHub Desktop.
Save saeedsh92/1fccf4c28ac96c4180465f9cda5b69d1 to your computer and use it in GitHub Desktop.
Convert dp to px and px to dp in Kotlin for Android
import android.content.Context
import android.content.res.Resources
import android.util.DisplayMetrics
/**
* Provides utilities for metrics.
*
* Original at:
* @see <a href="https://stackoverflow.com/a/9563438/8877070">stack overflow answer</a>
*
* @author kevin
*/
object MetricsUtil {
/**
* 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. If you don't have
* access to Context, just pass null.
* @return A float value to represent px equivalent to dp depending on device density
*/
fun convertDpToPixel(dp: Float, context: Context?): Float {
return if (context != null) {
val resources = context.resources
val metrics = resources.displayMetrics
dp * (metrics.densityDpi.toFloat() / DisplayMetrics.DENSITY_DEFAULT)
} else {
val metrics = Resources.getSystem().displayMetrics
dp * (metrics.densityDpi.toFloat() / DisplayMetrics.DENSITY_DEFAULT)
}
}
/**
* 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. If you don't have
* access to Context, just pass null.
* @return A float value to represent dp equivalent to px value
*/
fun convertPixelsToDp(px: Float, context: Context?): Float {
return if (context != null) {
val resources = context.resources
val metrics = resources.displayMetrics
px / (metrics.densityDpi.toFloat() / DisplayMetrics.DENSITY_DEFAULT)
} else {
val metrics = Resources.getSystem().displayMetrics
px / (metrics.densityDpi.toFloat() / DisplayMetrics.DENSITY_DEFAULT)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment