Android Convert Dp to Pixel - dpToPx (Kotlin)

June 18, 2018
and Pixel to Dip

NOTE: this feature coming soon to android-ktx

fun Int.dpToPx(displayMetrics: DisplayMetrics): Int = (this * displayMetrics.density).toInt()

fun Int.pxToDp(displayMetrics: DisplayMetrics): Int = (this / displayMetrics.density).toInt()

Usage

10.dpToPx(context.resources.displayMetrics)

I am tempted to use Resources.getSystem().displayMetrics to avoid passing in DisplayMetrics, but I am not sure how realiable it is.

This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.