1

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.

James Z
  • 12,209
  • 10
  • 24
  • 44
Ghost
  • 21
  • 4

1 Answers1

1

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)
Ayman Ait
  • 391
  • 2
  • 9
  • I've tried this solution along with with some other methods including changing font size programmatically but unfortunately they didn't worked for me. – Ghost Jul 14 '23 at 21:21