【问题标题】:Adjust font size based on screen size of smartphone React native根据智能手机屏幕大小调整字体大小 React native
【发布时间】:2019-03-27 06:14:01
【问题描述】:

大家好,我正在使用const {width,height} = Dimensions.get('window'); 根据屏幕宽度大小调整我的字体。 像这样使用....

fontSize:width/24

它在 iPhone 和 android 设备(如 5.5 英寸设备)中看起来不错,但在我的 Galaxy s9 中看起来很糟糕,我想根据屏幕设置字体,可以自行调整.. 我该怎么做呢

【问题讨论】:

标签: css react-native react-native-android react-native-ios


【解决方案1】:

为了获得设备的像素密度和字体比例,您可以根据docs 受益于PixelRatio

如文档中所述,PixelRatio.get() 为您提供设备像素密度:

var dynamic_fontSize = 20;
if(PixelRatio.get() === 1) {  // mdpi Android devices
    dynamic_fontSize = 12; 
} else if(PixelRatio.get() === 1.5) {  // hdpi Android devices
    ... 
}
else { ...

另一个想法是使用roundToNearestPixel() 来利用布局大小。 假设你想调整一个元素的大小以占据屏幕宽度的 98%(以 dp 为单位)和屏幕高度的 10%(以 dp 为单位):

export const widthPercentageToDP = widthPercent => {
  const screenWidth = Dimensions.get('window').width;
  // Convert string input to decimal number
  const elemWidth = parseFloat(widthPercent);  
  return PixelRatio.roundToNearestPixel(screenWidth * elemWidth / 100);
};

export const heightPercentageToDP = heightPercent => {
  const screenHeight = Dimensions.get('window').height;
  // Convert string input to decimal number
  const elemHeight = parseFloat(heightPercent); 
  return PixelRatio.roundToNearestPixel(screenHeight * elemHeight / 100);
};


这个帖子为你提供了一个清晰的例子:https://stackoverflow.com/a/35074379/4687359

【讨论】:

    【解决方案2】:

    使用这样的响应式库可以更好地处理事情。

    react-native-size-matters

    例如:

    import { scale, verticalScale, moderateScale } from 'react-native-size-matters';
    
    const Component = props =>
        <View style={{
            width: scale(30),
            height: verticalScale(50),
            padding: moderateScale(5)
        }}/>;
    

    因此,所有设备都会看起来更好。使用verticalScale 来定义与设备高度相关的事物。 scale 可以用于正常的事情。然后有一个自定义选项moderateScale,您也可以在其中手动定义缩放比例。

    更多详情请参考:Scaling React Native apps

    PS:还有其他选项,您可以手动定义自定义类来获取 PixelRatio 和所有内容。但这是一种直截了当的方法。

    参考PixelRatio Approach

    【讨论】:

    【解决方案3】:

    那么最好的选择是使用 vmax 和 vmin 单位。

    vmin:最小边的 1/100, vmax:最大边的1/100

    看看here

    【讨论】:

      猜你喜欢
      • 2017-11-02
      • 1970-01-01
      • 1970-01-01
      • 2017-01-19
      • 1970-01-01
      • 2017-12-02
      • 1970-01-01
      相关资源
      最近更新 更多