2

在我的 React Native 应用程序中,我有<Text>一些项目在某些手机上溢出并占用了两行。是否可以动态调整字体大小以确保文本适合一行?

4

1 回答 1

1

是的。您可以使用 react native 中的 pixelratio 和 dimensions 使用如下

import { Dimensions, Platform, PixelRatio } from 'react-native';

const {
  width: SCREEN_WIDTH,
  height: SCREEN_HEIGHT,
} = Dimensions.get('window');

//use your testing phone width to replace 320
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
  }
}

对于盒子样式,使用上面的方法如下。

const styles = {
  textStyle: {
    fontSize: normalize(12),
  },
};

当您想动态更改字体大小时,上述方法更准确。

但是,如果您只想将文本适合单行,您也可以使用 adjustsFontSizeToFit 如下

<View>
  <Text
    numberOfLines={1}
    adjustsFontSizeToFit
    style={{textAlign:'center',fontSize:50}}
  >
    YOUR_TEXT_HERE
  </Text>
</View>
于 2020-05-14T05:14:16.720 回答