React-Native:如何缩放字体大小以支持 Android 和 iOS 中的多种不同分辨率和屏幕?

2024-02-28

我在尝试在存在的许多不同屏幕上计算正确的字体大小时遇到​​了很大的麻烦。

目前我有一个名为的辅助函数getCorrectFontSizeForScreen.

export function getCorrectFontSizeForScreen(currentFontSize){

  const maxFontDifferFactor = 6; //the maximum pixels of font size we can go up or

  if(Platform.OS === 'ios'){    //iOS part
    let devRatio = PixelRatio.get();
    this.fontFactor = (((screenWidth*devRatio)/320)*0.55+((screenHeight*devRatio)/640)*0.45)
    if(this.fontFactor<=1){
      return currentFontSize-float2int(maxFontDifferFactor*0.3);
    }else if((this.fontFactor>=1) && (this.fontFactor<=1.6)){
      return currentFontSize-float2int(maxFontDifferFactor*0.1);
    }else if((this.fontFactor>=1.6) && (this.fontFactor<=2)){
      return currentFontSize;
    }else if((this.fontFactor>=2) && (this.fontFactor<=3)){
      return currentFontSize+float2int(maxFontDifferFactor*0.85);
    }else if (this.fontFactor>=3){
      return currentFontSize+float2int(maxFontDifferFactor);
    }
  }else{    //Android part

    let scale = screenWidth/375;  //got this from the f8 facebook project

    this.fontFactor = (((screenWidth)/320)*0.65+((screenHeight)/640)*0.35)

    if(this.fontFactor<=1){   //for 0.8 until 1.0 use 8 (800x600 phone this.fontFactor == 0.961)
      return float2int(scale * (currentFontSize+8));
    }else if((this.fontFactor>=1) && (this.fontFactor<=1.6)){ //for 1.0 until 1.5 use 4 (NEXUS 5 this.fontFactor == 1.055)
      return float2int(scale * (currentFontSize+4));
    }
    else{
      return float2int(scale * (currentFontSize+2));
    }
  }



function float2int (value) {
  return value | 0; //Converts a float to an integer
}

然后像这样标准化字体大小:

const styles = StyleSheet.create({
  aText:{
    color: 'white',
    fontFamily: 'Whatever',
    fontSize: getCorrectFontSizeForScreen(14),
  }
});

它似乎在 iOS 上运行良好,但在 Android 上运行得不太好...我想我需要更多的 fontFactor 组来通过反复试验来形成这个列表!

但我想知道,有没有更好的方法来做到这一点? 其他人对此做了什么?

谢谢你!


React Native 中的大小基于点,而不是像素,因此您不需要如此复杂的逻辑来根据设备 dpi 更改字体大小。相反,如果您想撤消自动应用的缩放,您应该将像素大小除以像素比率。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

React-Native:如何缩放字体大小以支持 Android 和 iOS 中的多种不同分辨率和屏幕? 的相关文章

随机推荐