Text Scaling in Jetpack compose

Text Scaling in Jetpack compose

TextScaling allows to increase and decrease the font size

Let's talk about how you would handle text scaling on a jetpack compose project. Text scaling is important as it helps people who cannot read small characters to increase the font size and the app's font size increases. Think of a situation where you might want the text not to scale past a certain font size or even not to scale at all... (This is necessary to maintain a good and appealing UI for the application as very large texts can make the UI feel unpleasant and unusable)

We will discuss two instances of how to handle text scaling.

  1. Preventing text from scaling and ensuring that the font size of that text is fixed to a certain font size

    To achieve this we will use an extension function

     val TextUnit.nonScaledSp
         @Composable
         get() = (this.value / LocalDensity.current.fontScale).sp
    

    usage::

     //sample text that we want the text not to scale but remain constant
      Text(text = "Non Scaling text", fontSize = 18.sp.nonScaledSp)
    
     //sample text that allows for scaling as phone's font size is changed
      Text(text = "Sample Scaling text", fontSize = 18.sp)
    
  2. Overriding the entire app's font scale

    This is where you want the text to scale but too large past a certain size just to ensure that even at large font sizes, the UI still looks good and texts are not overlapping and taking u too much space. You can achieve this by overriding attachBaseContext in the app's MainActivity

override fun attachBaseContext(newBase: Context?) {
        val newOverride = Configuration(newBase?.resources?.configuration)
        if (newOverride.fontScale >= 1.1f)
            newOverride.fontScale = 0.9f
        applyOverrideConfiguration(newOverride)
        super.attachBaseContext(newBase)
    }

You can play around with the font scale values to ensure you get a scaling that works for you

Reach out

X -> https://twitter.com/felixkariuki_

LinkedIn -> https://www.linkedin.com/in/felix-kariuki/

Github -> https://github.com/Felix-Kariuki

🥳 Happy coding