在compose开发中,text只能传入TextUnit类型的sp文字大小,sp会根据系统设置的文字大小、显示大小而改变,不符合我们的预期,以一下方式解决,直接贴代码:
@Composable
fun Int.nsp() = getRealDp(LocalContext.current, this.toDouble(), isDp = false).sp
@Composable
fun Float.nsp(): TextUnit = getRealDp(LocalContext.current, this.toDouble(), isDp = false).sp
@Composable
fun Double.nsp() = getRealDp(LocalContext.current, this, isDp = false).sp
@Composable
fun Int.ndp() = getRealDp(LocalContext.current, this.toDouble()).dp
@Composable
fun Float.ndp() = getRealDp(LocalContext.current, this.toDouble()).dp
@Composable
fun Double.ndp() = getRealDp(LocalContext.current, this).dp
private fun getRealDp(context: Context, value: Double, isDp: Boolean = true): Double {
val density =
if (isDp) context.resources.displayMetrics.density else context.resources.displayMetrics.scaledDensity
val screenWidth =
(if (context.resources.configuration.orientation == Configuration.ORIENTATION_LANDSCAPE) context.resources.displayMetrics.heightPixels else context.resources.displayMetrics.widthPixels) / 375
return screenWidth * 2 * value / density
}
375是蓝湖设计图尺寸的宽度,根据你自己的来即可