Skip to content

Instantly share code, notes, and snippets.

@kakajika
Last active Apr 25, 2020
Embed
What would you like to do?
Number extensions to convert px/dp/sp/pt/mm.
view.setPadding(20.dp.toPx, 20.dp.toPx, 20.dp.toPx, 20.dp.toPx)
/**
* px/dp/sp/pt/mm unit converter.
* This is not incompatible with Jetpack Compose.
*/
inline class Pixel(private val pxF: Float) {
val toPx: Int @Px get() = pxF.roundToInt()
fun toDp(res: Resources = Resources.getSystem()): Float = pxF / TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP, 1.0f, res.displayMetrics
)
fun toSp(res: Resources = Resources.getSystem()): Float = pxF / TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_SP, 1.0f, res.displayMetrics
)
fun toPt(res: Resources = Resources.getSystem()): Float = pxF / TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_PT, 1.0f, res.displayMetrics
)
fun toMm(res: Resources = Resources.getSystem()): Float = pxF / TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_MM, 1.0f, res.displayMetrics
)
companion object {
fun fromDp(dp: Float, res: Resources = Resources.getSystem()) = Pixel(TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP, dp, res.displayMetrics
))
fun fromSp(sp: Float, res: Resources = Resources.getSystem()) = Pixel(TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_SP, sp, res.displayMetrics
))
fun fromPt(pt: Float, res: Resources = Resources.getSystem()) = Pixel(TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_PT, pt, res.displayMetrics
))
fun fromMm(mm: Float, res: Resources = Resources.getSystem()) = Pixel(TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_MM, mm, res.displayMetrics
))
}
}
inline val Int.px get() = Pixel(pxF = this.toFloat())
inline val Float.px get() = Pixel(pxF = this)
inline val Int.dp get() = Pixel.fromDp(dp = this.toFloat())
inline val Float.dp get() = Pixel.fromDp(dp = this)
inline val Int.sp get() = Pixel.fromSp(sp = this.toFloat())
inline val Float.sp get() = Pixel.fromSp(sp = this)
inline val Int.pt get() = Pixel.fromPt(pt = this.toFloat())
inline val Float.pt get() = Pixel.fromPt(pt = this)
inline val Int.mm get() = Pixel.fromMm(mm = this.toFloat())
inline val Float.mm get() = Pixel.fromMm(mm = this)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment