Table of Contents
What to do when you really need to keep text from resizing and how to check how your composables look with different font scales using previews.
Before we start, preventing font scaling is not something you should use all of the time. Many people use the font scaling features on their devices to help them read what is on the screen. It is a very important accessibility feature.
Occasionally though, you may want to prevent the font from scaling if you have a component that must remain a specific size to fit your whole layout on a screen without scrolling, prevent text wrapping onto a new line or conform to a specification to be scanned, screenshot or read by something external to the device (such as a barcode scanner). When this is needed, you can prevent the font scaling on a case by case basis using a regular Jetpack Compose Text
composable.
Setting up font scaling previews
So we can observe different scaling variations in previews, we can make use of the fontScale
parameter available in the @Preview
annotation:
fontScale
allows a float value with 1.0f
equating to the normal, non-scaled font size. We can set a different value here and it will apply this scale setting to everything within the preview.
For my Pixel 6 Pro, I have four different font scale options, so I want to generate a set of previews for each scale level. So that I don’t need to repeat the @Preview
annotation set up every time and duplicate my previews for every scale level I have set up multipreview annotations as follows:
This results in the previews:
Preventing font scaling
When using the Jetpack Compose Text
composable we can set the font size using the fontSize
parameter. This takes a TextUnit
which can be a sp
or em
value.
If you are using em
then your font will not change size as the font scale changes as it is a relative font size. On the other hand sp
by definition is a measure of scaled pixels so will resize.
Usually, to make this reusable this would be defined as a variable elsewhere in your project or theme. But for my example, I will use 16.sp
as a value.
In the above previews, you can see that to access the font scale value we can make use of LocalDensity.current.fontScale
to detect the current scaling value.
To use this in our Text
composable, we can create a simple extension function that will divide our scaled TextUnit
value by the fontScale
amount to get the original ‘normal’, non-scaled value:
This can be then used for any Text
composable where a fixed size is needed:
By creating your extension on TextUnit
rather than Int
you can then use a font size from a theme or other dimension variables, making the code more reusable and more self documenting:
And as you can see when it is added to a preview, all the text is the same size!
To check out the full code, you can find it on github: