Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native - How to detect font size after a font scaling?

I need to detect what is the font size for text component after a font scaling. Let's say that I have a Text component with font size 18px

<Text style={{fontSize: 18}}>My Text</Text>

The user has set a large font through the OS accessibility settings. Now my text has been rendered with a larger font size (more than 18px). I'm aware that I can use allowFontScaling={false} but I don't want to lose the text accessibility. I saw that React native have an API for getting the font scale PixelRatio.getFontScale() but it doesn't work for iOS

Returns the scaling factor for font sizes. This is the ratio that is used to calculate the absolute font size, so any elements that heavily depend on that should use this to do calculations.

If a font scale is not set, this returns the device pixel ratio.

Currently this is only implemented on Android and reflects the user preference set in Settings > Display > Font size, on iOS it will always return the default pixel ratio. @platform android

Any ideas?

like image 448
0xori Avatar asked Mar 19 '18 16:03

0xori


People also ask

How do you handle font scaling in react native?

Restrict device font scaling. The last method to scale your React Native app allows you to apply an app-wide maximum font scale that any text element can reach. This means that whatever maximum font multiplier you set, the text in your app will never exceed that maximum size.


2 Answers

react-native-device-info provides a function, getFontScale(), which appears to work in both android and iOS.

like image 160
Pete Avatar answered Nov 08 '22 12:11

Pete


you can use useWindowDimensions

import { useWindowDimensions } from 'react-native';

const MyScreen = ({ navigation }) => {
   useWindowDimensions().fontScale // you will get current scale
}
like image 30
Ugur Avatar answered Nov 08 '22 12:11

Ugur