Skip to content

Measure text accurately before laying it out and get font information from your App.

License

Notifications You must be signed in to change notification settings

longgegege/react-native-text-size

 
 

Repository files navigation

React Native Text Size

npm Version License

Measure text accurately before laying it out and get font information from your App (Android and iOS).

There are two main functions: flatHeights to obtain the height of different blocks of text simultaneously, optimized for components such as <FlatList> or <RecyclerListView>.

The other one is measure, which gets detailed information about one block of text:

  • The width used by the text, with an option to calculate the real width of the largest line.
  • The height of the text, with or without paddings.
  • The number of lines.
  • The width of the last line.
  • Extended information of a given line.

The width and height are practically the same as those received from the onLayout event of a <Text> component with the same properties.

In both functions, the text to be measured is required, but the rest of the parameters are optional and work in the same way as with React Native:

  • fontFamily
  • fontSize
  • fontWeight
  • fontStyle
  • fontVariant (iOS)
  • includeFontPadding (Android)
  • textBreakStrategy (Android)
  • letterSpacing
  • allowFontScaling
  • width: Constraint for automatic line-break based on text-break strategy.

In addition, the library includes functions to obtain information about the fonts visible to the App.

If it has helped you, please support my work with a star ⭐️ or ko-fi.

Installation

Mostly automatic installation from npm

yarn add react-native-text-size
react-native link react-native-text-size

Change the compile directive to implementation in the dependencies block of the android/app/build.gradle file.

Requirements:

  • React Native v0.57 or later.
  • Android API 16 or iOS 9.0 and above.

For versions prior to 0.56 of React Native, please use react-native-text-size v2.1.1

See Manual Installation on the Wiki as an alternative if you have problems with automatic installation.

API

measure

measure(options: TSMeasureParams): Promise<TSMeasureResult>

This function measures the text as RN does and its result is consistent* with that of Text's onLayout event. It takes a subset of the properties used by <Text> to describe the font and other options to use.

If you provide width, the measurement will apply automatic wrapping in addition to the explicit line breaks.

* There may be some inconsistencies in iOS, see this Know Issue to know more.

Note:

Although this function is accurate and provides complete information, it can be heavy if the text is a lot, like the one that can be displayed in a FlatList. For these cases, it is better to use flatHeights, which is optimized for batch processing.

TSMeasureParams

Plain JS object with this properties (only text is required):

Property Type Default Notes
text string (none) This is the only required parameter and may include emojis or be empty, but it must not be null.
If this is an empty string the resulting width will be zero.
fontFamily string OS dependent The default is the same applied by React Native: Roboto in Android, San Francisco in iOS.
Note: Device manufacturer or custom ROM can change the default font.
fontWeight string 'normal' On android, numeric ranges has no granularity and '500' to '900' becomes 'bold', but you can use a fontFamily of specific weight ("sans-serif-thin", "sans-serif-medium", etc).
fontSize number 14 The default font size comes from RN.
fontStyle string 'normal' One of "normal" or "italic".
fontVariant array (none) iOS only
allowFontScaling boolean true To respect the user' setting of large fonts (i.e. use SP units).
letterSpacing number (none) Additional spacing between characters (aka tracking).
Note: In iOS a zero cancels automatic kerning.
All iOS, Android with API 21+
includeFontPadding boolean true Include additional top and bottom padding, to avoid clipping certain characters.
Android only
textBreakStrategy string 'highQuality' One of 'simple', 'balanced', or 'highQuality'.
Android only, with API 23+
width number MAX_INT Restrict the width. The resulting height will vary depending on the automatic flow of the text.
usePreciseWidth boolean false If true, the result will include an exact width and the lastLineWidth property.
You can see the effect of this flag in the sample App.
lineInfoForLine number (none) If >=0, the result will include a lineInfo property with information for the required line number.

The sample App shows interactively the effect of these parameters on the screen.

TSMeasureResult

measure returns a Promise that resolves to a JS object with this properties:

Property Type Notes
width number Total used width. It may be less or equal to the width option.
On Android, this value may vary depending on the usePreciseWidth flag.
height number Total height, including top and bottom padding if includingFontPadding was set (the default).
lastLineWidth number Width of the last line, without trailing blanks.
If usePreciseWidth is false (the default), this property is undefined.
lineCount number Number of lines, taking into account hard and automatic line breaks.
lineInfo object Line information.
If the lineInfoForLine option is not given, this property is undefined.

lineInfo

If the value of the lineInfoForLine is greater or equal than lineCount, this info is for the last line (i.e. lineCount - 1).

Property Type Notes
line number Line number of this info, base 0.
It can be less than the requested line number if lineInfoForLine is out of range.
start number Text offset of the beginning of this line.
end number Text offset after the last visible character (so whitespace is not counted) on this line.
bottom number The vertical position of the bottom of this line, including padding.
width number Horizontal extent of this line, including leading margin indent, but excluding trailing whitespace.
Use usePreciseWidth:true to get an accurate value for this property.

In case of error, the promise is rejected with an extended Error object with one of the following error codes, as a literal string:

Code Details
E_MISSING_PARAMETERS measure requires an object with the parameters, which was not provided.
E_MISSING_TEXT The text to measure is null or was not provided.
E_INVALID_FONT_SPEC The font specification is not valid. It is unlikely that this will happen on Android.
E_UNKNOWN_ERROR Well... who knows?

Example

//...
import rnTextSize, { TSFontSpecs } from 'react-native-text-size'

type Props = {}
type State = { width: number, height: number }

// On iOS 9+ will show 'San Francisco' and 'Roboto' on Android
const fontSpecs: TSFontSpecs = {
  fontFamily = undefined,
  fontSize = 24,
  fontStyle = 'italic',
  fontWeight = 'bold',
}
const text = 'I ❤️ rnTextSize'

class Test extends Component<Props, State> {
  state = {
    width: 0,
    height: 0,
  }

  async componentDidMount() {
    const width = Dimensions.get('window').width * 0.8
    const size = await rnTextSize.measure({
      text,             // text to measure, can include symbols
      width,            // max-width of the "virtual" container
      ...fontSpecs,     // RN font specification
    })
    this.setState({
      width: size.width,
      height: size.height
    })
  }

  // The result is reversible
  render() {
    const { width, height } = this.state
    return (
      <View style={{ padding: 12 }}>
        <Text style={{ width, height, ...fontSpecs }}>
          {text}
        </Text>
      </View>
    )
  }
}

flatHeights

flatHeights(options: TSHeightsParams): Promise<number[]>

Calculate the height of each of the strings in an array.

This is an alternative to measure designed for cases in which you have to calculate the height of numerous text blocks with common characteristics (width, font, etc), a typical use case with <FlatList> or <RecyclerListView> components.

The measurement uses the same algorithm as measure but it returns only the height of each block and, by avoiding multiple steps through the bridge, it is faster... much faster on Android!

I did tests on 5,000 random text blocks and these were the results (ms):

  measure flatHeights
Android 49,624 1,091
iOS 1,949 732

In the future I will prepare an example of its use with FlatList and multiple styles on the same card.

TSHeightsParams

This is an object similar to the one you pass to measure, but the text option is an array of strings and the usePreciseWidth and lineInfoForLine options are ignored.

Property Type Default
text string[] (none)
width number Infinity
fontFamily string OS dependent
fontWeight string 'normal'
fontSize number 14
fontStyle string 'normal'
fontVariant array (none)
allowFontScaling boolean true
letterSpacing number (none)
includeFontPadding boolean true
textBreakStrategy string 'highQuality'

The result is a Promise that resolves to an array with the height of each block (in SP), in the same order in which the blocks were received.

Unlike measure, null elements returns 0 without generating error, and empty strings returns the same height that RN assigns to empty <Text> components (the difference of the result between null and empty is intentional).

Example

//...
import rnTextSize, { TSFontSpecs } from 'react-native-text-size'

type Props = { texts: string[] }
type State = { heights: number[] }

// On iOS 9+ will show 'San Francisco' and 'Roboto' on Android
const fontSpecs: TSFontSpecs = {
  fontFamily = undefined,
  fontSize = 24,
  fontStyle = 'italic',
  fontWeight = 'bold',
}
const texts = ['I ❤️ rnTextSize', 'I ❤️ rnTextSize using flatHeights', 'Thx for flatHeights']

class Test extends Component<Props, State> {
  state = {
    heights: [],
  }

  async componentDidMount() {
    const { texts } = this.props
    const width = Dimensions.get('window').width * 0.8
    const heights = await rnTextSize.flatHeights({
      text: texts,      // array of texts to measure, can include symbols
      width,            // max-width of the "virtual" container
      ...fontSpecs,     // RN font specification
    })
    this.setState({
      heights
    })
  }

  render() {
    const { texts } = this.props
    const { heights } = this.state
    
    return (
      <View style={{ padding: 12 }}>
        {texts.map(
          (text, index) => (
            <Text style={{ height: heights[index], ...fontSpecs }}>
              {text}
            </Text>
          )
        )}
      </View>
    )
  }
}

specsForTextStyles

specsForTextStyles(): Promise<{ [key: string]: TSFontForStyle }>

Get system font information for the running OS.

This is a wrapper for the iOS UIFont.preferredFontForTextStyle method and the current Android Material Design Type Scale styles.

The result is a Promise that resolves to a JS object whose keys depend on the OS, but its values are in turn objects fully compatible with those used in the RN styles, so it can be used to stylize <Text> or <TextInput> components:

TSFontForStyle

Property Type Notes
fontFamily string System family name or font face.
fontSize number Font size in SP (unscaled).
fontStyle TSFontStyle Only if 'italic', undefined if the style is 'normal'.
fontWeight TSFontWeight Only if 'bold', undefined if the weight is 'normal'.
fontVariant TSFontVariant[] or null iOS only. Currently, no style includes this property.
letterSpacing number Omitted if running on Android with RN lower than 0.55

To know the key names, please see Keys from specsForTextStyles in the Wiki.

I have not tried to normalize the keys of the result because, with the exception of two or three, they have a different interpretation in each OS, but you can use them to create custom styles according to your needs.

fontFromSpecs

fontFromSpecs(specs: TSFontSpecs): Promise<TSFontInfo>

Returns the characteristics of the font obtained from the given specifications.

TSFontSpecs

This parameter is a subset of TSMeasureParams, so the details are omitted here.

Property Type Default
fontFamily string iOS: 'San Francisco', Android: 'Roboto'
fontWeight string 'normal'
fontSize number 14
fontStyle string 'normal'
fontVariant string[] (none)
letterSpacing number 0

fontFromSpecs uses an implicit allowsFontScaling:true and, since this is not a measuring function, includeFontPadding has no meaning.

TSFontInfo

The result is a Promise that resolves to a JS object with info for the given font and size, units in SP in Android or points in iOS, using floating point numbers where applicable*.

Property Type Details
fontFamily string In Android it is the same string passed as parameter.
fontName string iOS only, always undefined in Android.
fontSize number It may be different from the given parameter if the parameter includes decimals.
fontStyle string 'normal' or 'italic'.
fontWeight string 'normal' or 'bold', on iOS it can go from '100' to '900'.
fontVariant string[] iOS only, always undefined in Android.
ascender number The recommended distance above the baseline for singled spaced text.
descender number The recommended distance below the baseline for singled spaced text.
capHeight number iOS only Height of capital characters.
xHeight number iOS only Height of lowercase "x".
top number Android only. Maximum distance above the baseline for the tallest glyph in the font.
bottom number Android only. Maximum distance below the baseline for the lowest glyph in the font.
leading number The recommended additional space to add between lines of text.
lineHeight number The recommended line height. It should be greater if text contain Unicode symbols, such as emojis.
_hash number Hash code, may be useful for debugging.

* Using floats is more accurate than integers and allows you to use your preferred rounding method, but consider no more than 5 digits of precision in this values. Also, remember RN doesn't work with subpixels in Android and will truncate this values.

See more in:

Understanding typography at the Google Material Design site.

About Text Handling in iOS for iOS.

fontFamilyNames

fontFamilyNames(): Promise<string[]>

Returns a Promise for an array of font family names available on the system.

On iOS, this uses the UIFont.familyNames method of the UIKit.

On Android, the result is hard-coded for the system fonts and complemented dynamically with the fonts installed by your app, if any.

See About Android Fonts and Custom Fonts in the Wiki to know more about this list.

fontNamesForFamilyName

fontNamesForFamilyName(fontFamily: string): Promise<string[]>

Wrapper for the UIFont.fontNamesForFamilyName method of UIKit, returns an array of font names available in a particular font family.

You can use the rnTextSize's fontFamilyNames function to get an array of the available font family names on the system.

This is an iOS only function, on Android it always resolves to null.

Known Issues

Inconsistent width between platforms

In iOS, the resulting width of both, measure and flatHeights, includes leading whitespace while in Android these are discarded.

Incorrent height (iOS)

On iOS, RN takes into account the absolute position on the screen to calculate the dimensions. rnTextSize can't do that and both, width and height, can have a difference of up to 1 pixel (not point).

letterSpacing not scaling (iOS)

RN does not support the Dynamic Type Sizes, but does an excellent job imitating this feature through allowFontScaling ...except for letterSpacing that is not scaled.

I hope that a future version of RN solves this issue.

lineHeight Support

Although rnTextSize provides the resulting lineHeight in some functions, it does not support it as a parameter because RN uses a non-standard algorithm to set it. I recommend you do not use lineHeight unless it is strictly necessary, but if you use it, try to make it 30% or more than the font size, or use rnTextSize fontFromSpecs method if you want more precision.

Nested Text

Nested <Text> components (or with images inside) can be rasterized with dimensions different from those calculated, rnTextSize does not accept multiple sizes.

TODO

  • Normalized tracking or letter spacing in font info.
  • More testing, including Android and iOS TVs.
  • Learn the beautiful English, to make better docs.
  • Find something nice in the ugly Objective-C.

Support my Work

I'm a full-stack developer with more than 20 year of experience and I try to share most of my work for free and help others, but this takes a significant amount of time and effort so, if you like my work, please consider...

Of course, feedback, PRs, and stars are also welcome 🙃

Thanks for your support!

License

The BSD 2-Clause "Simplified" License.

© 2018-2019, Alberto Martínez. All rights reserved.

About

Measure text accurately before laying it out and get font information from your App.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • TypeScript 59.7%
  • C++ 35.6%
  • JavaScript 2.5%
  • CMake 2.2%