React Native Responsive Font Size
You can use PixelRatio
for example:
var React = require('react-native');var {StyleSheet, PixelRatio} = React;var FONT_BACK_LABEL = 18;if (PixelRatio.get() <= 2) { FONT_BACK_LABEL = 14;}var styles = StyleSheet.create({ label: { fontSize: FONT_BACK_LABEL }});
Edit:
Another example:
import { Dimensions, Platform, PixelRatio } from 'react-native';const { width: SCREEN_WIDTH, height: SCREEN_HEIGHT,} = Dimensions.get('window');// based on iphone 5s's scaleconst scale = SCREEN_WIDTH / 320;export function normalize(size) { const newSize = size * scale if (Platform.OS === 'ios') { return Math.round(PixelRatio.roundToNearestPixel(newSize)) } else { return Math.round(PixelRatio.roundToNearestPixel(newSize)) - 2 }}
Usage:
fontSize: normalize(24)
you can go one step further by allowing sizes to be used on every <Text />
components by pre-defined sized.
Example:
const styles = { mini: { fontSize: normalize(12), }, small: { fontSize: normalize(15), }, medium: { fontSize: normalize(17), }, large: { fontSize: normalize(20), }, xlarge: { fontSize: normalize(24), },};
We use a simple, straight-forward, scaling utils functions we wrote:
import { Dimensions } from 'react-native';const { width, height } = Dimensions.get('window');//Guideline sizes are based on standard ~5" screen mobile deviceconst guidelineBaseWidth = 350;const guidelineBaseHeight = 680;const scale = size => width / guidelineBaseWidth * size;const verticalScale = size => height / guidelineBaseHeight * size;const moderateScale = (size, factor = 0.5) => size + ( scale(size) - size ) * factor;export {scale, verticalScale, moderateScale};
Saves you some time doing many ifs. You can read more about it on my blog post.
Edit: I thought it might be helpful to extract these functions to their own npm package, I also included
ScaledSheet
in the package, which is an automatically scaled version of StyleSheet
.You can find it here: react-native-size-matters.
adjustsFontSizeToFit
and numberOfLines
works for me. They adjust long email into 1 line.
<View> <Text numberOfLines={1} adjustsFontSizeToFit style={{textAlign:'center',fontSize:30}} > {this.props.email} </Text></View>