react-native 適配裝置解析度問題
阿新 • • 發佈:2019-01-10
同一資料夾下,分別新建以下幾個檔案:
新建global.js檔案,程式碼如下:
import { Dimensions, PixelRatio, Platform, Alert } from 'react-native'; import HttpUtils from './HttpUtils' import FontSize from './TextSize' import {px2dp} from './Px2dp' const { height, width } = Dimensions.get('window'); // 系統是iOS global.iOS = (Platform.OS === 'ios'); // 系統是安卓 global.Android = (Platform.OS === 'android'); // 獲取螢幕寬度 global.SCREEN_WIDTH = width; // 獲取螢幕高度 global.SCREEN_HEIGHT = height; // 獲取螢幕解析度 global.PixelRatio = PixelRatio.get(); // 最小線寬 global.pixel = 1 / PixelRatio; global.HttpUtils=HttpUtils; global.FONT_SIZE = FontSize; global.px2dp = px2dp;
新建Px2dp.js檔案,程式碼如下:
import { AsyncStorage, Platform, } from 'react-native'; export default { async isLogin() { const data = await AsyncStorage.getItem('TOKEN'); // console.log(data); if (data === null) { console.log('false'); global.TOKEN = false; return false; } else { console.log('true'); global.TOKEN = true; return true; } } } // 設計圖上的比例,寬度 const basePx = Platform.OS === 'ios' ? 750 : 720; exports.px2dp = function px2dp(px: number): number { return px / basePx * (global.SCREEN_WIDTH); };
新建TextSize.js檔案,程式碼如下:
const TextSize = (size) => { if (global.PixelRatio === 2) { // iphone 5s and older Androids if (global.SCREEN_WIDTH < 360) { return size * 0.95; } // iphone 5 if (global.SCREEN_HEIGHT < 667) { return size; // iphone 6-6s } else if (global.SCREEN_HEIGHT >= 667 && global.SCREEN_HEIGHT <= 735) { return size * 1.15; } // older phablets return size * 1.25; } if (global.PixelRatio === 3) { // catch Android font scaling on small machines // where pixel ratio / font scale ratio => 3:3 if (global.SCREEN_WIDTH <= 360) { return size; } // Catch other weird android width sizings if (global.SCREEN_HEIGHT < 667) { return size * 1.15; // catch in-between size Androids and scale font up // a tad but not too much } if (global.SCREEN_HEIGHT >= 667 && global.SCREEN_HEIGHT <= 735) { return size * 1.2; } // catch larger devices // ie iphone 6s plus / 7 plus / mi note 等等 return size * 1.27; } if (global.PixelRatio === 3.5) { // catch Android font scaling on small machines // where pixel ratio / font scale ratio => 3:3 if (global.SCREEN_WIDTH <= 360) { return size; // Catch other smaller android height sizings } if (global.SCREEN_HEIGHT < 667) { return size * 1.20; // catch in-between size Androids and scale font up // a tad but not too much } if (global.SCREEN_HEIGHT >= 667 && global.SCREEN_HEIGHT <= 735) { return size * 1.25; } // catch larger phablet devices return size * 1.40; } // if older device ie pixelRatio !== 2 || 3 || 3.5 return size; }; module.exports = TextSize; // eslint-disable-line no-undef
在index.js檔案中,引入Global.js檔案即可。
import './src/method/Global.js'
針對設計圖為750的寬。
使用方法:
在設定樣式時,如設定
寬width:px2dp(400),
字型fontSize:FONT_SIZE(16)
注:數字為你從設計圖上量到的尺寸。