Skip to content

Instantly share code, notes, and snippets.

@EmmanuelMess
Created October 1, 2018 14:45
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 EmmanuelMess/9cb33c2bbde2655064a1ec0aab14ce9a to your computer and use it in GitHub Desktop.
Save EmmanuelMess/9cb33c2bbde2655064a1ec0aab14ce9a to your computer and use it in GitHub Desktop.
Intuitive Dp to Px and Px to Dp converter in kotlin
import android.content.res.Resources
val Int.px: Pixels
get() = Pixels(this.toFloat())
val Int.dp: DensityPixels
get() = DensityPixels(this.toFloat())
/*inline*/ class Pixels(val value: Float) {
fun toInt() = value.toInt()
fun toDp() = DensityPixels(value / Resources.getSystem().displayMetrics.density)
}
/*inline*/ class DensityPixels(val value: Float) {
fun toInt() = value.toInt()
fun toPx(): Pixels = Pixels(value * Resources.getSystem().displayMetrics.density)
}
@EmmanuelMess
Copy link
Author

EmmanuelMess commented Oct 1, 2018

If you are working in Kotlin 1.3 or later use inline class instead of class (uncomment /*inline*/).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment