I would like to ask how react native handle or do the responsive font. For example in iphone 4s i Have fontSize: 14, while in iphone 6 I have fontSize: 18.
You can use something like this.
var {height, width} = Dimensions.get('window'); var textFontSize = width * 0.03;
inputText: {
color : TEXT_COLOR_PRIMARY,
width: '80%',
fontSize: textFontSize
}
Hope this helps without installing any third party libraries.
Take a look at the library I wrote: https://github.com/tachyons-css/react-native-style-tachyons
It allows you to specify a root-fontSize (rem
) upon start, which you can make dependent of your PixelRatio
or other device-characteristics.
Then you get styles relative to your rem
, not only fontSize, but paddings etc. as well:
<Text style={[s.f5, s.pa2, s.tc]}>
Something
</Text>
Expanation:
f5
is always your base-fontsizepa2
gives you padding relative to your base-fontsize.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>
Need to use this way I have used this one and it's working fine.
react-native-responsive-screen npm install react-native-responsive-screen --save
Just like I have a device 1080x1920
The vertical number we calculate from height **hp**
height:200
200/1920*100 = 10.41% - height:hp("10.41%")
The Horizontal number we calculate from width **wp**
width:200
200/1080*100 = 18.51% - Width:wp("18.51%")
It's working for all device
A slightly different approach worked for me :-
const normalize = (size: number): number => {
const scale = screenWidth / 320;
const newSize = size * scale;
let calculatedSize = Math.round(PixelRatio.roundToNearestPixel(newSize))
if (PixelRatio.get() < 3)
return calculatedSize - 0.5
return calculatedSize
};
Do refer Pixel Ratio as this allows you to better set up the function based on the device density.
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 device
const 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.
ScaledSheet
in the package, which is an automatically scaled version of StyleSheet
.
You can find it here: react-native-size-matters.