[英]Prevent system font scaling - Jetpack Compose
我正在嘗試限制應用程序不受系統字體縮放的影響。 我經歷了許多解決方案,但沒有一個幫助。 他們中的大多數人告訴使用 dp 而不是 dp 來表示文本大小,但是在撰寫中我們只能使用 sp 如果我是正確的,因為它需要一個文本單元。 是否有任何正確的方法來限制我們使用 jetpack compose 完成的應用程序中的字體縮放? 請幫忙。
您可以像這樣對Int
或Float
進行擴展
@Composable
fun Int.scaledSp(): TextUnit {
val value: Int = this
return with(LocalDensity.current) {
val fontScale = this.fontScale
val textSize = value / fontScale
textSize.sp
}
直到 jetpack compose for Text()
沒有解決方案,您可以使用 AndroidView:
@Composable
fun CustomText(
// attributes you need to set
){
AndroidView(factory = { context ->
AppCompatTextView(context).apply {
setTextSize(TypedValue.COMPLEX_UNIT_DIP, 25)
setText("")
// other attributes you want to set or other features which is not available in jetpack compose now.
}
},)
}
這種方式可以成功。
@Composable
fun DisableFontScale(content: @Composable () -> Unit) {
val density = LocalDensity.current.density
CompositionLocalProvider(
LocalDensity provides Density(
density = density,
fontScale = 1f
),
content = content
)
}
@Composable
fun EnableFontScale(content: @Composable () -> Unit) {
val density = LocalDensity.current.density
val fontScale = LocalContext.current.resources.configuration.fontScale
CompositionLocalProvider(
LocalDensity provides Density(
density = density,
fontScale = fontScale
),
content = content
)
}
@Composable
fun Example() {
Column {
Text(text = "This will be scaled.")
DisableFontScale {
Text(text = "This will not be scaled.")
EnableFontScale {
Text(text = "We enable font scale, so this will be scaled.")
}
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.