问题
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
回答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.
回答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 dp to pixel values for fonts.
PixelRatio
回答3:
You can use a package like
react-native-pixel-perfect
Good Luck!
来源:https://stackoverflow.com/questions/48250554/dealing-with-font-size-units-in-react-native-dp-sp-px