0

Hey guys im using const {width,height} = Dimensions.get('window'); to adjust my font based on screen width size. using like this....

fontSize:width/24

its looks good in iPhone and android device like 5.5 inch device but in my Galaxy s9 it looks horrible I want to set my font based on screen which can be adjust by itself.. how can I do it

Tanveerbyn
  • 764
  • 1
  • 10
  • 25

3 Answers3

0

Then the best option is to use vmax and vmin units.

vmin: 1/100th of the smallest side, vmax: 1/100th of the largest side

take a look at it here

Dulara Malindu
  • 1,477
  • 4
  • 18
  • 37
0

Use a responsive ilibrary like this that will handle things better.

react-native-size-matters

Eg:

import { scale, verticalScale, moderateScale } from 'react-native-size-matters';

const Component = props =>
    <View style={{
        width: scale(30),
        height: verticalScale(50),
        padding: moderateScale(5)
    }}/>;

Thus things will look better in all devices. Use verticalScale for defining things relative to height of the device. scale can be used for normal things .. then there is a custom option moderateScale where u can manually define the scaling ratio as well.

For more details refer : Scaling React Native apps

PS: there are other options as well where u can manually define a custom class to get the PixelRatio and everything. but this is a straight forward approach.

Refer PixelRatio Approach

Victor
  • 4,171
  • 1
  • 29
  • 37
0

In order to get access to the device's pixel density and font scale, you can benefit from PixelRatio according to the docs.

As indicated in the docs, PixelRatio.get() provides you with the device pixel density:

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

Another idea is to make use of the layout size using roundToNearestPixel(). Let's imagine you want to adjust the size of an element to take over 98% of the screen’s width in dp and 10% of the screen’s height in 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);
};


This thread provides you with a clear example: https://stackoverflow.com/a/35074379/4687359

A. Nadjar
  • 2,440
  • 2
  • 19
  • 20