Text size issue in Jetpack Compose

826 Views Asked by At

I'm working on a specific device which has Physical density: 160. For the design I'm following a link of xd adobe and placing elements according to it. Adobe give me size of text in px which I'm converting it into sp and providing it in textSize but is not working properly, text size different in actual screen.

enter image description here

size of this text is 203x100 but in adobe it is 194x96 with same textSize.

I've tried pixel calculator to convert the proper values from px to sp but it is not working at all.

2

There are 2 best solutions below

1
Ayman Ait On

The simple explanation is that the unit of text sp takes in consideration the screen dpi and the default device font size it means if you increase the font size from accessibility settings of the phone your apps text will scale automatically which is the preferred behavior actually. If you think that you app must not increase it's text size even if the accessibility settings say so then you need to create a new unit for yourself:

@Composable
fun Int.scaledSp(): TextUnit {
val value: Int = this
return with(LocalDensity.current) {
      val fontScale = this.fontScale
      val textSize =  value / fontScale
            textSize.sp
      }
    
val Int.scaledSp:TextUnit
@Composable get() =  scaledSp()
   

Credits to @Thracian Now you can use it normally as you use your normal text Unit for exemple :

Text(text = "Hello World", fontSize = 20.scaledSp)
0
Gourav Dadhich On

follow this instructions

1 . add this dependency

          implementation("com.intuit.ssp:ssp-android:1.0.6")
          implementation("com.intuit.sdp:sdp-android:1.1.0")

2 . add this code to utils folder or anywhere you want

val Int.sdp: Dp
    @Composable
    get() = this.sdpGet()

val Int.ssp: TextUnit
    @Composable get() = this.textSdp(density = LocalDensity.current)

@Composable
private fun Int.textSdp(density: Density): TextUnit = with(density) {
    [email protected]()
}

@Composable
private fun Int.sdpGet(): Dp {

    val id = when (this) {
        in 1..600 -> "_${this}sdp"
        in (-60..-1) -> "_minus${this}sdp"
        else -> return this.dp
    }

    val resourceField = getFieldId(id)
    return if (resourceField != 0) dimensionResource(id = resourceField) else this.dp

}

@Composable
private fun getFieldId(id: String): Int {
    val context = LocalContext.current
    return context.resources.getIdentifier(id, "dimen", context.packageName)

}

Now your able to use them Example :

textSize -> Text("Hello World!",fontSize = 12.ssp)

dimen -> Image(
               painter = painterResource(id = infoItemsList[currentPage].image),
               contentDescription = "",
               modifier = Modifier.size(250.sdp)
          )