Skip to content

Commit 53cc08f

Browse files
refactor(*): 优化sp转px
1 parent 8a6c418 commit 53cc08f

File tree

1 file changed

+7
-2
lines changed
  • lite/src/main/java/com/pengxh/kt/lite/extensions

1 file changed

+7
-2
lines changed

lite/src/main/java/com/pengxh/kt/lite/extensions/Float.kt

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,12 @@
11
package com.pengxh.kt.lite.extensions
22

33
import android.content.Context
4+
import android.util.TypedValue
45
import java.math.RoundingMode
56
import java.text.DecimalFormat
67

8+
private val decimalFormat = DecimalFormat("#")
9+
710
/**
811
* px转dp
912
*/
@@ -22,8 +25,10 @@ fun Float.dp2px(context: Context): Float {
2225
* sp转px
2326
*/
2427
fun Float.sp2px(context: Context): Float {
25-
val decimalFormat = DecimalFormat("#")
28+
val floatValue = TypedValue.applyDimension(
29+
TypedValue.COMPLEX_UNIT_SP, this, context.resources.displayMetrics
30+
)
2631
decimalFormat.roundingMode = RoundingMode.CEILING
27-
val result = decimalFormat.format(this / context.getScreenDensity())
32+
val result = decimalFormat.format(floatValue)
2833
return result.toFloat()
2934
}

0 commit comments

Comments
 (0)