React Native不同設備分辨率適配和設計稿尺寸單位px的適配


React Native中使用的尺寸單位是dp(一種基於屏幕密度的抽象單位。在每英寸160點的顯示器上,1dp = 1px),而設計師使用的是px, 這兩種尺寸如何換算呢?

官方提供了PixelRatio進行pt到px的轉換
import {PixelRatio} from 'react-native';
const dp2px = dp=>PixelRatio.getPixelSizeForLayoutSize(dp);
const px2dp = px=>PixelRatio.roundToNearestPixel(px);
設計師給你一個尺寸,比如100px*200px的View,按照下面的方式可實現設計還原:

View style={{width:px2dp(100),height:px2dp(200),backgroundColor:"red"}}
如果每個地方都這樣寫會很麻煩,於是我們就有了下面轉換代碼

import {PixelRatio,Dimensions}} from 'react-native';
const dp2px = dp=>PixelRatio.getPixelSizeForLayoutSize(dp);
const px2dp = px=>PixelRatio.roundToNearestPixel(px);
let designSize = {width:720,height:1280}; //假設設計尺寸為:720*1280
let pxRatio = PixelRatio.get();
let win_width = Dimensions.get("window").width;
let win_height = Dimensions.get("window").height;
let width = dp2px(win_width);
let height = dp2px(win_height);
let design_scale = designSize.width/width;
height = height*design_scale
let scale = 1/pxRatio/design_scale;
實際使用:
要在最外層View上設置如下樣式:

const styles = StyleSheet.create({
container: {
width: width,
height: height,
transform: [{translateX: -width * .5}, {translateY: -height * .5}, {scale: scale}, {translateX: width * .5}, {translateY: height * .5}]
}
});
在后續的開發中將不必再關注適配的問題,只需要按照設計師給的尺寸實現布局即可,比如設計稿中的圖片尺寸是300px*300px,你的樣式中就寫 width: 300,height: 300,

這里就寫設計稿上的300px 300px,不用帶單位
image: {
width:300,
height:300
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM