Created
December 5, 2025 05:10
-
-
Save benigumocom/3af986ba2bd45835489d815aa4198a26 to your computer and use it in GitHub Desktop.
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
| private val Context.density: Float | |
| get() = resources.displayMetrics.density | |
| private val Context.scale: Float | |
| get() = resources.displayMetrics.scaledDensity | |
| /* ----- dp(Dp) → px(Float) ----- */ | |
| fun Context.dpToPx(dp: Dp): Float = | |
| dp.value * density | |
| /* ----- dp(Dp) → sp(TextUnit) ----- */ | |
| fun Context.dpToSp(dp: Dp): TextUnit = | |
| (dp.value * density / scale).sp | |
| /* ----- px(Float) → dp(Dp) ----- */ | |
| fun Context.toDp(px: Float): Dp = | |
| (px / density).dp | |
| /* ----- px(Float) → sp(TextUnit) ----- */ | |
| fun Context.toSp(px: Float): TextUnit = | |
| (px / scale).sp | |
| /* ----- sp(TextUnit) → dp(Dp) ----- */ | |
| fun Context.spToDp(sp: TextUnit): Dp = | |
| (sp.value * scale / density).dp | |
| /* ----- sp(TextUnit) → px(Float) ----- */ | |
| fun Context.spToPx(sp: TextUnit): Float = | |
| sp.value * scale | |
| /* ----- from Dp ----- */ | |
| fun Dp.toPx(context: Context): Float = context.dpToPx(this) | |
| fun Dp.toSp(context: Context): TextUnit = context.dpToSp(this) | |
| /* ----- from px(Float) ----- */ | |
| fun Float.toDp(context: Context): Dp = context.toDp(this) | |
| fun Float.toSp(context: Context): TextUnit = context.toSp(this) | |
| /* ----- from sp(TextUnit) ----- */ | |
| fun TextUnit.toPx(context: Context): Float = context.spToPx(this) | |
| fun TextUnit.toDp(context: Context): Dp = context.spToDp(this) |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How dp/sp/px Conversion Works in Android
https://android.benigumo.com/20251205/how-dp-sp-px-conversion/
dp / px / sp 完全相互変換
https://note.com/chanzma/n/n06d2e4fabda7