2

I have problem with scaling font inside of View or better to say inside of Text component in React Native for Android. The problem is, I want to text inside of Text component automatically scale depends on length of string (if text can fit inside View with desired font size do nothing and if it's string too long for this font size set smaller font size).

For Example:

1.

<View style={{flexDirection: 'row'}}> <Text numberOfLines={1} style={{fontSize: 20}}>This is in one row.</Text> </View>

In this case (1.) text would render in one line with font size 22.

2.

<View style={{flexDirection: 'row'}}> <Text numberOfLines={1} style={{fontSize: 20}}>This is in one row and much longer text inside of Text component.</Text> </View>

In second (2.) scenario text would render in one line with ... at the end and also with font size 20. But, I want to font automatically scale down if content can't fit in one line of Text component.

I search for solution and I found that for iOS you can easily solve this problem with attributes inside Text as following:

<Text adjustsFontSizeToFit minimumFontScale={.4}>Automatically font scale</Text>

This isn't working for Android so I really need help :/

If someone knows how I can accomplish to font automatically change size to fit inside of Text in one line I would be very grateful.

Thank you in advance!

Newie
  • 61
  • 2
  • 3

2 Answers2

4

If you have the maximum width of the Text and its length in characters, you can calculate the fontSize that will fit. Something like textWidth / textLength = fontWidth. However, it is highly unlikely the fontWidth (The width available for each character) will be exactly the same as the respective fontSize. But if you find the widest character in your font, and find the correlation between its width and the fontSize, you can calculate the fontSize through fontSize / fontWidth = c. Therefore, the width will always be smaller than the maximum.

For example, I found that for the Roboto Light font, a fontSize of 30 results in a width of 28,8px for the m, the widest character in this case. Thus, the fontSize is 30/28,8 times bigger than the actual width. So we can calculate it through textWidth / textLength = fontSize / (30 / 28,8)

This value can be adjusted if you have any extra spacing in your characters, and if you want a minimum font size, you can use Math.max(updatedFontSize, minimumFontSize)

Filipe
  • 866
  • 5
  • 16
2

The thing is you need to specify the width for your Text element. Please do take a look at the link.

  • 1
    Hi Kosalram, I tried with solution given at your link but it's not working for **Android**. If string is longer than width constraint it's rendered with ... (three dots). This is not what I want. I want to font become smaller and all content fit into Text. – Newie Jul 11 '18 at 15:07