Dealing with font size units in react native (Dp, Sp, px..)
Solution 1
On Android:
px
- raw pixels
- Ignores the device's screen density. (e.g. on high-res screen stuff may show up very small)
- Ignores the user's font size settings if used for text.
dp
- density-independent pixels
- Changes based on the device's screen density.
- Ignores the user's font size settings if used for text.
sp
- scalable pixels
- Changes based on the device's screen density.
- The size adapts based on the user's font size settings. (Should only be used for texts)
On React Native:
- Texts act as
sp
on Android - The rest acts like
dp
What can be confusing is that the React Native website says the following:
All dimensions in React Native are unitless, and represent density-independent pixels.
If you are taking the definition of "density-independent pixels" from the Android native world described above, then you could make the false assumption that texts are also handled as density-independent pixels(dp
) whereas they work like sp
respecting the user's font size settings as they should.
Solution 2
The PixelRatio API of react native might be what you are looking for.
It has methods like getPixelSizeForLayoutSize()
and roundToNearestPixel()
which can help you convert from dp to pixel values for fonts.
otavio1992
Updated on June 04, 2022Comments
-
otavio1992 almost 2 years
I'm beginning to develop with React native and I'm currently building my first app. I got handed some Zepplin Files telling me how each screen must be (including some code in android xml format), including fontSize and spacing, the problem is, it's in DP, and sometimes SP.. It doesn't tell me the pixel density or anything else, so I can't just use the same number in my app. What should I do in this case? How do you guys handle different units when making your react native app?
Here is a code sample I have to change to react native code:
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="18.7sp" android:fontFamily="sans-serif-medium" android:textStyle="normal" android:textColor="#ffffff" android:lineSpacingExtra="-18.7sp" tools:text="60" />
And:
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="32sp" android:fontFamily="sans-serif-medium" android:textStyle="normal" android:textColor="#70c300" android:lineSpacingExtra="-32sp" tools:text="20" />
Any help is appreciated
-
Nithyanandan Sathiyanathan over 3 yearsIf Zepline is maintained wit while applying the pt values in react native for example: Button width is mentioned as 259pt when am applying width as 259 it does not match with the UX. I applied width as 300 then it matches with UX. do i need to request UX team to convert pt to PX for development ?