同一文件夹下,分别新建以下几个文件:
新建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)
注:数字为你从设计图上量到的尺寸。