Last active
April 25, 2020 05:16
-
-
Save kakajika/eb03c22bff506c969fc7344a80a01e88 to your computer and use it in GitHub Desktop.
Number extensions to convert px/dp/sp/pt/mm.
This file contains hidden or 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
view.setPadding(20.dp.toPx, 20.dp.toPx, 20.dp.toPx, 20.dp.toPx) |
This file contains hidden or 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
/** | |
* 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