Skip to content Skip to sidebar Skip to footer

How To Adjust Font Size To Fit View In React Native For Android?

How I can make the font size of the text auto change inside a view in react native? I have text with different lengths, some of which doesn't fit the view so decreased the font siz

Solution 1:

A bit improved Jeffy Lee code worked for me

constAdjustLabel = ({
  fontSize, text, style, numberOfLines
}) => {
  const [currentFont, setCurrentFont] = useState(fontSize);

  return (
    <TextnumberOfLines={numberOfLines }
      adjustsFontSizeToFitstyle={ [style, { fontSize:currentFont }] }
      onTextLayout={ (e) => {
        const { lines } = e.nativeEvent;
        if (lines.length > numberOfLines) {
          setCurrentFont(currentFont - 1);
        }
      } }
    >
      { text }
    </Text>
  );
};

Solution 2:

Try this approach. Consider setting the font size according to screen width as following

width: Dimensions.get('window').width

So in your style try to make a percentage calculation to make the font size fit the screen

style={
  text:{
     fontSize:0.05*width
  }
}

this will gonna work for all screens (both Android and IOS)

Solution 3:

Try this method.

I used the method onLayout to achieve this.

First, I wrapped my Text view inside a fixed size View, then I implement onLayout for both view, so that I can get the height of the fixed size View and the height of the Text view.

Next, if the Text view's required height is more than the height of our View, we decrease the font size of our Text view until the height can fit into our View.

Herein the test code, I made 2 Views, one in pink and one in yellow background, the font size of Text inside the pink View will be adjust to fit the View and the yellow Text will remain the same font size.

importReact, { useState, useEffect } from'react';
import { StyleSheet, Text, View } from'react-native';

exportdefaultfunctionApp() {
  const [size, setSize] = useState(20)
  const [viewHeight, setViewHeight] = useState(0)
  const [textHeight, setTextHeight] = useState(0)

  useEffect(() => {
    if (textHeight > viewHeight) {
      setSize(size - 1) // <<< You may adjust value 1 to a smaller value so the text can be shrink more precisely
    }
  }, [textHeight])

  return (
    <Viewstyle={styles.container}><Viewstyle={{margin:20,
          backgroundColor: 'pink',
          width:200,
          height:200
        }}
        onLayout={(event) => {
          var { x, y, width, height } = event.nativeEvent.layout;
          setViewHeight(height)
        }}
      >
        <Textstyle={{fontSize:size,
          }}
          onLayout={(event) => {
            var { x, y, width, height } = event.nativeEvent.layout;
            setTextHeight(height)
          }}
        >
          Gemma is a middle grade novel that follows a curious explorer and her ring-tailed lemur, Milo, 
          as they hunt for the “most greatest treasure in the world”. Solving riddles, battling a bell-wearing 
          jaguar, and traveling the Eight Seas, Gemma’s adventures take her from a young girl to a brave captain, 
          whose only limits are the stars.
        </Text></View><Viewstyle={{margin:20,
          backgroundColor: 'yellow',
          width:200,
          height:200
        }}
      ><Textstyle={{fontSize:20
          }}
        >
          Gemma is a middle grade novel that follows a curious explorer and her ring-tailed lemur, Milo, 
          as they hunt for the “most greatest treasure in the world”. Solving riddles, battling a bell-wearing 
          jaguar, and traveling the Eight Seas, Gemma’s adventures take her from a young girl to a brave captain, 
          whose only limits are the stars.
        </Text></View></View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

You may notice the pink Text's font is having a shrinking animation when the font size is decreasing, I suggest that you can initial the Text opacity with 0 and after the font adjustment finish set it to 1 so user wont see the ugly animation.

Solution 4:

Edit

I faced an even more challenging task recently. The task was to fit multiple words with different lengths (eg: Both Plane and Truck have the same character count, but Truck is longer than Plane when written in the same font size.) in Views (one word for each view) of the same size. I used the React Native Animated library to achieve this. Input words -> Plane, Truck, Bus, Car, Cab

  1. Rendered all the given words using the Text component with a fixed, preferably larger font size that exceeds the required width for the longest word.
  2. Found the width and the height(heights already similar) of the longest word using the onLayout function of Text Component.
  3. Calculated the scale factors (which would be less than 1 due to the assumption in step 1.) along the X-axis and Y-axis needed to fit the largest word within the fixed View and took the minimum of those 2.
  4. Then rendered each word in a Text component (with the same font size) wrapped with a View component just fitting the Text and scaled each View with the same scale factor using transform prop.

I implemented the above idea since continuously decreasing font size until the word fits the View using onLayout was visible on the screen to the user, no matter which trick I used to hide it during the running time of the algorithm. I have published an npm package for this: https://www.npmjs.com/package/@chamodanethra/react-native-fitted-text

Solution 5:

I had a similar issue with the number of text resizing the views (user inputs string into an input field currently limited to 30 characters) in my React Native app. I noticed there are a few properties already implemented for iOS: adjustsFontSizeToFit minimumFontScale={.4} however the Android does not have such methods available at this time.

Note: Solution which works for me but might not be the "best" possible!

Currently, I'm using a nested ternary operator:

fontSize: this.props.driverName.length > 12 && 
this.props.driverName.length < 20 ? heightPercentageToDP('2%') : 
this.props.driverName.length > 20 && this.props.driverName.length < 40 
? heightPercentageToDP('1.75%') : heightPercentageToDP('2.25%')

In layman's terms, the above ternary checks the range of characters used and based off the range modifies the fontSize into a '%' inside the view. The method: heightPercentageToDP is a function which I am using to convert the size into a '%' based on the mobile screen's DP (this way it is responsive on a tablet or a mobile phone).

heightPercentageToDP Code Snippet:

import { Dimensions, PixelRatio } from"react-native";
    constwidthPercentageToDP = widthPercent => {
    const screenWidth = Dimensions.get("window").width;
    // Convert string input to decimal numberconst elemWidth = parseFloat(widthPercent);
    returnPixelRatio.roundToNearestPixel((screenWidth * elemWidth) / 100);
    };
    constheightPercentageToDP = heightPercent => {
    const screenHeight = Dimensions.get("window").height;
    // Convert string input to decimal numberconst elemHeight = parseFloat(heightPercent);
    returnPixelRatio.roundToNearestPixel((screenHeight * elemHeight) / 100);
    };
    export { widthPercentageToDP, heightPercentageToDP };

Credit and source for heightPercentageToDP goes to: https://medium.com/react-native-training/build-responsive-react-native-views-for-any-device-and-support-orientation-change-1c8beba5bc23.

Post a Comment for "How To Adjust Font Size To Fit View In React Native For Android?"