React Native Responsive Font Size

前端 未结 14 1162
执念已碎
执念已碎 2020-11-29 16:39

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.

相关标签:
14条回答
  • 2020-11-29 17:20

    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 scale
    const 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),
      },
    };
    
    0 讨论(0)
  • 2020-11-29 17:20
    import { Dimensions } from 'react-native';
    
    const { width, fontScale } = Dimensions.get("window");
    
    const styles = StyleSheet.create({
        fontSize: idleFontSize / fontScale,
    });
    

    fontScale get scale as per your device.

    0 讨论(0)
提交回复
热议问题