Created
October 1, 2018 14:45
-
-
Save EmmanuelMess/9cb33c2bbde2655064a1ec0aab14ce9a to your computer and use it in GitHub Desktop.
Intuitive Dp to Px and Px to Dp converter in kotlin
This file contains 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
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) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If you are working in Kotlin 1.3 or later use
inline class
instead ofclass
(uncomment/*inline*/
).