Preface
React Native can develop apps for ios and android. During the development process, you will inevitably encounter the problem of screen adaptation (IOS screens of several sizes and Android screens of various sizes). The following is a way to solve RN adaptation with a few lines of code!
Pre-proper knowledge of screen adaptation
The unit of dimensions in RN is dp, while the unit of the design draft is px
principle
Although the units are different, the proportion of the screen width of the element is the same
Use the unchanged screen ratio of elements to convert px to dp (in this way, if the screen adaptation is achieved, the elements will be enlarged or reduced in a larger or smaller ratio under different screens)
The formula is as follows:
Design draft element width (px) / Total design draft width (px) = element width (dp) / Total screen width (dp)
What we require is the width of the element (dp)
It can be concluded:
Element width (dp) = Design draft element width (px) * Total screen width (dp) / Total design draft width (px)
Code implementation
// import { Dimensions } from 'react-native'; // Equipment width, unit dpconst deviceWidthDp = ('window').width; // Design draft width (here is 640px), unit pxconst uiWidthPx = 640; // px to dp (px in the design draft to dp in rn)export const pTd = (uiElePx) => { return uiElePx * deviceWidthDp / uiWidthPx; }
use
Every time you set the dimension style to an element, use the pTd() function (pass into the actual px of the element in the design draft).
The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.