Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React-Native: How to scale font size to support many different resolutions and screens in both Android and iOS?

Tags:

I have huge trouble trying to figure the correct font size on the many different screens that exist.

Currently I have a helper function called 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
}

and then normalize the font size like this:

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

It seems to work well on iOS but not that well on Android... I guess I need more fontFactor groups to form this list with trial and error!!

But I wonder, is there a better way to do this? What do others do about this?

Thank you!

like image 841
SudoPlz Avatar asked Jul 12 '16 09:07

SudoPlz


1 Answers

Sizes in React Native are based on points, not pixels, hence you shouldn't need such a complex logic to change font size according to the device dpi. At the contrary, if you want to undo the scaling automatically applied you should divide the pixel size for the pixel ratio.

like image 192
Nuthinking Avatar answered Sep 28 '22 03:09

Nuthinking